java – 用Gson分析JSON地图/字典?

前端之家收集整理的这篇文章主要介绍了java – 用Gson分析JSON地图/字典?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要解析一下 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文档,但无法弄清楚如何正确地将字典反序列化为地图.

解决方法

Gson很容易处理一个JSON对象的反序列化,其名称为:值对到Java Map.

以下是使用原始问题的JSON的示例. (此示例还演示如何使用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);
  }
}
原文链接:https://www.f2er.com/java/126738.html

猜你在找的Java相关文章