java 使用 Gson 解析 JSON 地图/字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6362587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing JSON maps / dictionaries with Gson?
提问by Will Curran
I need to parse a JSON Response that looks like:
我需要解析如下所示的 JSON 响应:
{"key1": "value1",
"key2": "value2",
"key3":
{"childKey1": "childValue1",
"childKey2": "childValue2",
"childKey3": "childValue3" }
}
class Egg {
@SerializedName("key1")
private String mKey1;
@SerializedName("key2")
private String mKey2;
@SerializedName("key3")
// ???
}
I'm reading through the Gson docs but cannot figure out how to properly deserialize a dictionary to a Map.
我正在阅读 Gson 文档,但无法弄清楚如何将字典正确反序列化为 Map。
回答by Programmer Bruce
Gson readily handles deserialization of a JSON object with name:value pairs into a Java Map
.
Gson 可以轻松地将具有名称:值对的 JSON 对象反序列化为 Java Map
。
Following is such an example using the JSON from the original question. (This example also demonstrates using a FieldNamingStrategy
to avoid specifying the serialized name for every field, provided that the field-to-element name mapping is consistent.)
以下是使用原始问题中的 JSON 的示例。(此示例还演示了使用 aFieldNamingStrategy
来避免为每个字段指定序列化名称,前提是字段到元素的名称映射是一致的。)
import java.io.FileReader;
import java.lang.reflect.Field;
import java.util.Map;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Foo
{
public static void main(String[] args) throws Exception
{
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingStrategy(new MyFieldNamingStrategy());
Gson gson = gsonBuilder.create();
Egg egg = gson.fromJson(new FileReader("input.json"), Egg.class);
System.out.println(gson.toJson(egg));
}
}
class Egg
{
private String mKey1;
private String mKey2;
private Map<String, String> mKey3;
}
class MyFieldNamingStrategy implements FieldNamingStrategy
{
//Translates the Java field name into its JSON element name representation.
@Override
public String translateName(Field field)
{
String name = field.getName();
char newFirstChar = Character.toLowerCase(name.charAt(1));
return newFirstChar + name.substring(2);
}
}
回答by Zuljin
As far as I remember you should create separate class for each json object. Try something like this:
据我所知,您应该为每个 json 对象创建单独的类。尝试这样的事情:
class Key {
@SerializedName("childKey1")
private String mchildKey1;
@SerializedName("childKey2")
private String mchildKey2;
@SerializedName("childKey3")
private String mchildKey3;
}
class Egg {
@SerializedName("key1")
private String mKey1;
@SerializedName("key2")
private String mKey2;
@SerializedName("key3")
private Key mKey3;
}
If this is not what you expected you can write your own serialize/deserialize adapter.
如果这不是您所期望的,您可以编写自己的序列化/反序列化适配器。