如何在java中读取json字符串?
这是我的json字符串:如何在java中读取json字符串?,java,json,Java,Json,这是我的json字符串: [ { "id": 1, "ip": "192.168.0.22", "folderName": "gpio1_pg3" }, { "id": 2, "ip": "192.168.0.22", "folderName": "gpio2_pb16" } ] 我想对数组进行迭代,因为我将为每个数组成员创建一个特殊的对象 这是我从http url获
[
{
"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。或者是将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;
}
或者是用于将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;
}
试试看
试试看
创建具有字段id、ip和folderName的类,使用jackson binder将数据绑定到自定义对象列表创建具有字段id、ip和folderName的类,使用jackson binder将数据绑定到自定义对象列表
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(your json string);