Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to jsonobject in java [closed]

This is string from jsonObject

[
    {
        "No": "1",
        "Name": "ABC"
    },
    {
        "No": "2",
        "Name": "PQR"
    },
    {
        "No": "3",
        "Name": "XYZ"
    }
]

I want convert to this string to JSONObject to get this value in JSONArray

like image 242
Nitin Karale Avatar asked Oct 16 '13 10:10

Nitin Karale


People also ask

What does JSON object toString do?

A JSONObject constructor can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get and opt methods, or to convert values into a JSON text using the put and toString methods.

What is the difference between JSON object and JSON object?

JSONObject is "native" to Android SDK, JsonObject is probably the one from Gson library, the one that I use. Two different package, don't work with both ;) choose one. I had some issue with the date formatting in JSONObject.


2 Answers

Use this one:

import org.json.JSONArray;
// ...

String jsonStr = "[{\"No\":\"1\",\"Name\":\"ABC\"},{\"No\":\"2\",\"Name\":\"PQR\"},{\"No\":\"3\",\"Name\":\"XYZ\"}]";

   JSONArray array = new JSONArray(jsonStr); 

    for(int i=0; i<array.length(); i++){
        JSONObject jsonObj  = array.getJSONObject(i);
        System.out.println(jsonObj.getString("No"));
        System.out.println(jsonObj.getString("Name"));
    }

Output:

1
ABC
2
PQR
3
XYZ
like image 62
Maxim Shoustin Avatar answered Oct 22 '22 00:10

Maxim Shoustin


Use Google's JSON library (google-gson):

JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(your json string);
like image 41
mqshen Avatar answered Oct 22 '22 00:10

mqshen