【发布时间】: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