-4

如何在 Java 中创建这种 json 以及如何解析它

[["Car","Bike","Bus"],["Road","Footpath","Highway"],["Horn","Sound","Pollution"]]

我对java很陌生。有人请帮忙

4

2 回答 2

2

使用org.json Java 解析器,您可以将 JSON 创建为

JSONArray jsonObj1 = new JSONArray();
jsonObj1.put("Car").put("Bike").put("Bus");

System.out.println(jsonObj1); // ["Car","Bike","Bus"]

JSONArray jsonObj2 = new JSONArray();
jsonObj2.put("Road").put("Footpath").put("Highway");

System.out.println(jsonObj2); // ["Road","Footpath","Highway"]

JSONArray jsonObj3 = new JSONArray();
jsonObj3.put("Horn").put("Sound").put("Sound");

System.out.println(jsonObj3); // ["Horn","Sound","Pollution"]

JSONArray jsonRoot = new JSONArray();
jsonRoot.put(jsonObj1).put(jsonObj2).put(jsonObj3);

System.out.println(jsonRoot);
// prints: [["Car","Bike","Bus"],["Road","Footpath","Highway"],["Horn","Sound","Pollution"]]

反序列化 JSON 字符串也很简单

String jsonString = jsonRoot.toString();
JSONArray jsonParsedRoot = new JSONArray(jsonString);
System.out.println(jsonParsedRoot.getJSONArray(0).getString(1)); // Bike
于 2013-08-20T22:29:48.937 回答
0

有关此主题的 Java EE 7 文档和示例:http: //docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm

于 2013-08-20T23:10:48.583 回答