【问题标题】:How to read json string in java? [duplicate]如何在java中读取json字符串? [复制]
【发布时间】:2016-03-01 12:15:07
【问题描述】:

这是我的 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。

【问题讨论】:

标签: java json


【解决方案1】:

JacksonGSON 是用于将 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;
}

【讨论】:

    【解决方案2】:

    试试,

    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"));
    }
    

    或者您可以尝试使用 Google 的 JSON 库 (google-gson)

    JsonParser jsonParser = new JsonParser();
    JsonElement element = jsonParser.parse(your json string);
    

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 2013-01-07
      • 1970-01-01
      相关资源
      最近更新 更多