Parsing JSON maps / dictionaries with Gson?

前端 未结 2 2175
时光说笑
时光说笑 2021-02-19 11:21

I need to parse a JSON Response that looks like:

{\"key1\": \"value1\", 
 \"key2\": \"value2\", 
 \"key3\": 
    {\"childKey1\": \"childValue1\", 
     \"childKe         


        
相关标签:
2条回答
  • 2021-02-19 12:06

    As far as I remember you should create separate class for each json object. Try something like this:

    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.

    0 讨论(0)
  • 2021-02-19 12:19

    Gson readily handles deserialization of a JSON object with name:value pairs into a 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.)

    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);
      }
    }
    
    0 讨论(0)
提交回复
热议问题