如何读取java中的json字符串?
问题描述:
这是我的JSON字符串:如何读取java中的json字符串?
[
{
"id": 1,
"ip": "192.168.0.22",
"folderName": "gpio1_pg3"
},
{
"id": 2,
"ip": "192.168.0.22",
"folderName": "gpio2_pb16"
}
]
我想要遍历有关阵列,因为我将创建为每个阵列成员的特殊对象。
这是如何从http url获取json字符串的方式。
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inputStreams, Charset.forName("UTF-8")));
String jsonText = readAll(bufferedReader);
你可以给我一个例子,我如何得到一个所有json元素的数组。 一个数组元素必须包含id,ip和folderName。
答
Jackson或GSON是用于将JSON字符串转换为对象或映射的流行库。
杰克逊例如:
String json = "[{\"foo\": \"bar\"},{\"foo\": \"biz\"}]";
JsonFactory f = new JsonFactory();
JsonParser jp = f.createJsonParser(json);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT)) {
Foo foobar = mapper.readValue(jp, Foo.class);
// process
// after binding, stream points to closing END_OBJECT
}
public class Foo {
public String foo;
}
答
尝试,
JSONArray array = new JSONArray(jsonStr);
for(int i=0; i<array.length(); i++){
JSONObject jsonObj = array.getJSONObject(i);
System.out.println(jsonObj.getString("id"));
System.out.println(jsonObj.getString("ip"));
System.out.println(jsonObj.getString("folderName"));
}
或者您也可以使用谷歌的JSON库尝试(谷歌GSON)
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(your json string);
创建带有字段ID类,IP和folderName,使用jackson binder将数据绑定到自定义对象列表 – Pragnani
http://stackoverflow.com/questions/6697147/jso正迭代贯通jsonarray – IceJOKER