Java 如何解析 JSON 并将其值转换为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2255220/
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-13 05:18:19  来源:igfitidea点击:

How to parse a JSON and turn its values into an Array?

javajson

提问by TIMEX

public static void parseProfilesJson(String the_json){
       try {
            JSONObject myjson = new JSONObject(the_json);

            JSONArray nameArray = myjson.names();
            JSONArray valArray = myjson.toJSONArray(nameArray);
            for(int i=0;i<valArray.length();i++)
            {
                String p = nameArray.getString(i) + "," + ValArray.getString(i);
                Log.i("p",p);
            }       

        } catch (JSONException e) {
                e.printStackTrace();
        }
    }

As you can see, this sample code will print out the KEYof the JSONs, followed by the VALUESof the JSONS.

如您所见,此示例代码将打印出JSON的KEY,然后是 JSONS 的VALUES

It would print profiles, johnif the json was like this:

如果json是这样的它会打印配置文件,约翰

{'profiles':'john'}

That's cool. That's fine, as I can work with those variables. However, what if the JSON was like this:

这很酷。没关系,因为我可以处理这些变量。但是,如果 JSON 是这样的呢:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

In this case, the entire value would be the array. Basically, I just want to grab that array (which is the "value" in this case)...and turn it into an actual array that JAVA could use. How can I do that? Thanks.

在这种情况下,整个值将是数组。基本上,我只想获取该数组(在本例中为“值”)……并将其转换为 JAVA 可以使用的实际数组。我怎样才能做到这一点?谢谢。

采纳答案by Buhake Sindi

for your example:

对于您的示例:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

你将不得不做一些这样的事情:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

这将返回数组对象。

Then iterating will be as follows:

然后迭代如下:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0)starts with [character).

您必须确定数据是否为数组(只需检查charAt(0)[字符开头)。

Hope this helps.

希望这可以帮助。

回答by rputta

You can prefer quick-json parser to meet your requirement...

您可以更喜欢 quick-json 解析器来满足您的要求...

quick-json parser is very straight forward, flexible, very fast and customizable. Try this out

quick-json 解析器非常直接、灵活、非常快速和可定制。试试这个

[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -

[quick-json 解析器] ( https://code.google.com/p/quick-json/) - quick-json 功能 -

  • Compliant with JSON specification (RFC4627)

  • High-Performance JSON parser

  • Supports Flexible/Configurable parsing approach

  • Configurable validation of key/value pairs of any JSON Heirarchy

  • Easy to use # Very Less foot print

  • Raises developer friendly and easy to trace exceptions

  • Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered

  • Validating and Non-Validating parser support

  • Support for two types of configuration (JSON/XML) for using quick-json validating parser

  • Require JDK 1.5 # No dependency on external libraries

  • Support for Json Generation through object serialization

  • Support for collection type selection during parsing process

  • 符合 JSON 规范 (RFC4627)

  • 高性能 JSON 解析器

  • 支持灵活/可配置的解析方法

  • 任何 JSON 层次结构的键/值对的可配置验证

  • 易于使用 # 非常少的足迹

  • 提高开发人员友好且易于跟踪的异常

  • 可插入的自定义验证支持 - 键/值可以通过在遇到时配置自定义验证器来验证

  • 验证和非验证解析器支持

  • 支持使用 quick-json 验证解析器的两种类型的配置(JSON/XML)

  • 需要 JDK 1.5 # 不依赖外部库

  • 通过对象序列化支持 Json 生成

  • 支持解析过程中的集合类型选择

For e.g.

例如

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);