简体   繁体   English

如何读取 JSON 数组并将它们存储在 stringbuilder 中以显示它?

[英]How to read the JSON array and store them in a stringbuilder to display it?

I have a json file which is somthing like我有一个类似的 json 文件

{ "44451":["67","188","188E","188R","982E","301"]} { "44451":["67","188","188E","188R","982E","301"]}

How do I read the strings inside of " 44451 " and display it in a StringBuilder in android studio?如何读取“ 44451 ”中的字符串并将其显示在android studio的StringBuilder中?

Help would be appreciated.帮助将不胜感激。 Thanks.谢谢。

JSONObject json = new JSONObject(jsonString);
JSONArray jArray = json.getJSONArray("44451");


StringBuilder sb;
for(int i=0; i<jArray.length(); i++){
sb.append(jArray.getJSONObject(i).toString());
}

Don't really understand the StringBuilder aspect, but if you want to read the whole text from the JSON, then you can do this.不是很了解 StringBuilder 方面,但是如果您想从 JSON 中读取整个文本,那么您可以这样做。

the whole text is an Object Because it surrounded with { } , the you have an key 44451 assign to an array ["67",...] .整个文本是一个对象 因为它被{ }包围,所以你有一个键44451分配给一个数组["67",...]

to read this, you will read the object first then read the content of the array.要读取此内容,您将首先读取对象,然后读取数组的内容。

JSONObject object = new JSONObject('');
JSONArray array = object.getJSONArray("44451");
for (int i = 0; i < array.length(); i++) { 
 String value = array[i];
 // other opetations as desired..
}

I would recommend to use FasterXML Jackson library because you can parse JSON into arbitrary user defined types.我建议使用FasterXML Jackson库,因为您可以将 JSON 解析为任意用户定义的类型。 You could add it a gradle dependency like this您可以将其添加为这样的 gradle 依赖项

compile 'com.fasterxml.jackson.core:jackson-databind:2.6.2'
compile 'com.fasterxml.jackson.core:jackson-core:2.6.2'

Then you can parse your JSON like this.然后你可以像这样解析你的JSON。

String json = "{ \"44451\":[\"67\",\"188\",\"188E\",\"188R\",\"982E\",\"301\"]}";

ObjectMapper mapper = new ObjectMapper();
Map<String, List<String>> values = mapper.readValue(json, new TypeReference<Map<String, List<String>>>() {
});

StringBuilder str = new StringBuilder();
for (String value : values.get("44451")) {
    // do whatever you want 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM