使用Gson解析JSON映射/字典?

2022-09-04 02:16:41

我需要解析一个 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")
    // ???
}

我正在阅读Gson文档,但无法弄清楚如何将字典正确地反序列化为Map。


答案 1

Gson 很容易将具有 name:value 对的 JSON 对象反序列化处理为 Java 。Map

下面是使用原始问题中的 JSON 的示例。(此示例还演示如何使用 a 来避免为每个字段指定序列化名称,前提是字段到元素名称的映射是一致的。FieldNamingStrategy

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);
  }
}

答案 2

据我所知,您应该为每个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;
}

如果这不是您期望的,您可以编写自己的序列化/反序列化适配器。