【问题标题】:How to serialize json string using GSON and extract key and value from it?如何使用 GSON 序列化 json 字符串并从中提取键和值?
【发布时间】:2014-08-01 03:40:45
【问题描述】:

我正在尝试使用 GSON 解析我的 JSON 字符串,并从简单的 json 字符串中提取键:值对并将其加载到地图中。截至目前,我正在使用org.json.simple.parser.JSONParser 来做到这一点。现在我正在尝试使用 GSON 做同样的事情。

下面是我的json字符串jsonstringA-

{"description":"Hello World.","hostname":"abc1029.dc3.host.com","ipaddress":"100.671.1921.219","hostid":"/tt/rt/v2/dc3/111","file_timestamp":"20140724","software_version":"v13","commit_hash":"abcdefg"}

现在我需要序列化上面的 JSON 字符串并从 json stringg 中提取下面的字段并将其作为键值对放入 map m 中。在地图中的含义应该是 description 作为键和 Hello World 作为值。其他人也是如此。

public static final Set<String> MAPPING_FIELDS = new HashSet<String>(Arrays.asList(
        "description", "hostname", "ipaddress", "hostid", "software_version"));

private final static JSONParser parser = new JSONParser();


parseJSONData(jsonstringA, MAPPING_FIELDS);

public Map<String, String> parseJSONData(String jsonStr, Set<String> listOfFields) {
    Map<String, String> m = new HashMap<String, String>();
    try {
        Object obj = parser.parse(jsonStr);
        org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) obj;
        if (jsonObject != null) {
            for (String field : listOfFields) {
                String value = (String) jsonObject.get(field);
                m.put(field, value);
            }
        }
    } catch (ParseException e) {
        // log exception here
    }
    return m;
}

我如何在这里使用 GSON 来做同样的事情?

【问题讨论】:

标签: java json serialization gson


【解决方案1】:

这很简单。只需创建一个 POJO,其变量与 JSON 字符串中使用的变量相同。

查看Gson#fromJson(Reader,Type)的Java Doc

示例代码:

class ClientDetail {
    private String description;
    private String hostname;
    private String ipaddress;
    private String hostid;
    private String file_timestamp;;
    private String software_version;
    private String commit_hash;
    // getter & setter
}

BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
ClientDetail data = new Gson().fromJson(reader, ClientDetail.class);

您可以将其转换为Map,也可以使用TypeToken 将其转换为预期的类型。

示例代码:

BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> data = new Gson().fromJson(reader, type);

【讨论】:

  • 我得到了 gson 字符串。如何处理我这里没有json.txt 的这种情况??
  • 探索更多关于 'Gson.fromJson()' 的重载方法
猜你喜欢
  • 1970-01-01
  • 2013-01-18
  • 1970-01-01
  • 2023-03-18
  • 2015-08-29
  • 2019-11-24
  • 1970-01-01
  • 2016-05-27
  • 2011-02-07
相关资源
最近更新 更多