0

This is my Json String and I am trying to fetch the value of Entity.I am a beginner in using JSON.

[
    {
        "_id": "john",
        "preferences": [
            {
                "Entity": [
                    "IBM",
                    "Pfizer"
                ]
            },
            {
                "Topic": "Pharma"
            }
        ]
    }
]

Can anyone help me on this?

Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43
Shilpa
  • 1
  • 1

3 Answers3

0

try as follow :

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

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

Swarna Sekhar Dhar
  • 550
  • 1
  • 8
  • 25
0

You can use gson library. If your input is a JSON string, you first need to parse it using a JsonParser object which returns us a JsonElement which is converted into JsonArray as the input Json is an array. You then extract the first object from it using get(0) and then convert it into a JsonObject, extract preferences element as JsonArray and follow similar procedure to get Entity.

        String jsonString = "[" +
            "    {" +
            "        \"_id\": john," +
            "        \"preferences\": [" +
            "            {" +
            "                \"Entity\": [" +
            "                    IBM," +
            "                    Pfizer" +
            "                ]" +
            "            }," +
            "            {" +
            "                \"Topic\": Pharma" +
            "            }" +
            "        ]" +
            "    }" +
            "]";

    JsonArray jsonArray = new JsonParser().parse(jsonString).getAsJsonArray();

    JsonArray preferences = jsonArray.get(0).getAsJsonObject().get("preferences").getAsJsonArray();
    JsonArray entity = preferences.get(0).getAsJsonObject().get("Entity").getAsJsonArray();
Anurag Paul
  • 147
  • 8
0
import org.json.*;


JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

May be it may helps you: Parse JSON in Java

Ws Memon
  • 107
  • 7