TIMEX
TIMEX

Reputation: 271674

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

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 KEY of the JSONs, followed by the VALUES of the JSONS.

It would print profiles, john if the json was like this:

{'profiles':'john'}

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

{'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.

Upvotes: 37

Views: 174992

Answers (3)

thebiggestlebowski
thebiggestlebowski

Reputation: 2779

The other answers in this question assume you have a java object to work with. I wanted to be able to get values from an arbitrary json structure, one for which I didn't necessarily have the corresponding java object.

My idea is field keys of the form "key":value". Now, each line of the result contains up to one value which can be put into a list/array. I also remove json scope delimiters, ie, "[]{},".

My solution makes some assumptions:

  1. You use double quotes in your json.

  2. The json is pretty formatted.

    public static String getOnlyJsonValues(String json) {
        json = json.replaceAll("\\{", "");
        json = json.replaceAll("}", "");
        json = json.replaceAll("\\[", "");
        json = json.replaceAll("]", "");
        json = json.replaceAll("\".*?\":", "");
        return json;
    }
    

Now, you just need to parse the output into a list of Strings:

    public static List<String> parseUniqueValues(String json) {
        List<String> values = new ArrayList<>();
        String onlyValues = getOnlyJsonValues(json);

        try {
            StringReader stringReader = new StringReader(onlyValues);
            BufferedReader bufReader = new BufferedReader(stringReader);
            String line;
            while ((line = bufReader.readLine()) != null) {
                if (line.endsWith(",")) {
                    line = line.substring(0, line.length() - 1);
                }
                if (line.startsWith("\"") && line.endsWith("\"")) {
                    line = line.substring(1, line.length() - 1);
                }


                line = line.trim();
                if (line.length() > 0) {
                    values.add(line);
                }
                
            }
        } catch (IOException e) {
            LOG.warn("Unable to read lines in String:" + onlyValues);
        }

        return values;
    }

Upvotes: 1

rputta
rputta

Reputation: 935

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

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

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

  • 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

For e.g.

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

Upvotes: 1

Buhake Sindi
Buhake Sindi

Reputation: 89169

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).

Hope this helps.

Upvotes: 58

Related Questions