如何在java中读取json字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35722646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:03:24  来源:igfitidea点击:

How to read json string in java?

javajson

提问by Andreas Fritsch

This is my json-string:

这是我的 json 字符串:

[
    {
        "id": 1,
        "ip": "192.168.0.22",
        "folderName": "gpio1_pg3"
    },
    {
        "id": 2,
        "ip": "192.168.0.22",
        "folderName": "gpio2_pb16"
    }
]

I want to iterate about the array, because I will create an special object for each array member.

我想遍历数组,因为我将为每个数组成员创建一个特殊对象。

This is the way how I get the json string from an http url.

这就是我从 http url 获取 json 字符串的方式。

BufferedReader bufferedReader = 
         new BufferedReader(new InputStreamReader(inputStreams, Charset.forName("UTF-8")));

String jsonText = readAll(bufferedReader);

Could you give me an example how I can get an Array of all json-elements. One array-element have to contain the id, ip, and folderName.

你能给我举个例子,我怎样才能得到一个包含所有 json 元素的数组。一个数组元素必须包含 id、ip 和 folderName。

采纳答案by Yusuf K.

Hymansonor GSONare popular libraries for converting JSON strings to objects or maps.

HymansonGSON是用于将 JSON 字符串转换为对象或映射的流行库。

Hymanson example:

Hyman逊示例:

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

回答by Rakesh KR

Try,

尝试,

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

OR you can try with Google's JSON library (google-gson)

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

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