kittu88
kittu88

Reputation: 2461

json parsing from string type variable

I have a String type variable like this:

String response_str="[{"Code":"AC_70","Id":1,"Lat":23.847153,"Lon":88.254636,"Name":"Rejinagar"},{"Code":"AC_51","Id":2,"Lat":25.024795,"Lon":88.118248,"Name":"Englishbazar"}]
";

Now, I have created a method, like this:

public void parse_json_str(String json_str)
    {


        Log.i("String: ",json_str);


    }

I went through the tutorial here and got a method to do it.

private void JsonParsing() {
  JSONObject jObject;
  String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\",   \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
  try {
   jObject = new JSONObject(jString);

   JSONObject menuObject = jObject.getJSONObject("menu");
   String attributeId = menuObject.getString("id");
   System.out.println(attributeId);

   String attributeValue = menuObject.getString("value");
   System.out.println(attributeValue);

   JSONObject popupObject = menuObject.getJSONObject("popup");
   JSONArray menuitemArray = popupObject.getJSONArray("menuitem");

   for (int i = 0; i < 3; i++) {
    Log.i("Value",menuitemArray.getJSONObject(i)
      .getString("value").toString());
    Log.i("Onclick:", menuitemArray.getJSONObject(i).getString(
      "onclick").toString());
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

The problem is that, the JSONs are of different structures, I want to parse my json in the same way. My json does not contain any mother node. Any suggestions on how to parse the json will be of great help.

Upvotes: 1

Views: 614

Answers (1)

Klawikowski
Klawikowski

Reputation: 615

You should take a closer look at the structure. This JSON is an array with 2 objects. So after creating JSONArray you should iterate through all possible JSON Objects in it.

[
   {
      "Code":"AC_70",
      "Id":1,
      "Lat":23.847153,
      "Lon":88.254636,
      "Name":"Rejinagar"
   },
   {
      "Code":"AC_51",
      "Id":2,
      "Lat":25.024795,
      "Lon":88.118248,
      "Name":"Englishbazar"
   }
]

Code:

private void JsonParsing()
{
    JSONArray lJSONArray;
    String jString = "your JSON here";
    try
    {
        lJSONArray = new JSONArray( jString );

        JSONObject lJSONObject;
        for ( int i = 0; i < lJSONArray.length(); i++ )
        {
            lJSONObject = lJSONArray.getJSONObject( i );
            // PARSE FIELD HERE
            String lCode = lJSONObject.getString( "Code" );
            // ETC

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

}

try with this :)

Upvotes: 2

Related Questions