1

I am not much experienced in JSON, so the question might be a little trivial, but I can not sort this out. I have a simple JSON string like:

["{\"__type:\"GeoPoint\",\"latitude\":51.165691,\"longitude\":10.451526}","{\"__type:\"GeoPoint\",\"latitude\":20.593684,\"longitude\":78.96288}"]

I want to parse the JSON and get the values in different variables. I have implemented the below code snippet but it is not working as expected. I can see no log after parsing the JSON. The code:

String jsonString = arg0.get(i).get(0).getJSONArray("tripPoints").toString();
                                Log.e("Json String", jsonString);
                                 JSONArray jsonarray;
                                try {
                                    jsonarray = new JSONArray(jsonString);
                                    for(int j=0; j<jsonarray.length(); j++){
                                        JSONObject obj = jsonarray.getJSONObject(j);

                                        String latitude = obj.getString("latitude");
                                        String longitude = obj.getString("longitude");

                                        Log.e("triplatitude", latitude);
                                        Log.e("triplongitude", longitude);
                                    }   
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

What should I do to get the data from the JSON? Where am I going wrong?

kittu88
  • 2,451
  • 5
  • 40
  • 80
  • What does the log Log.e("Json String", jsonString); say in the logcat? What exception is throwed in de logcat? – Dion Segijn Dec 05 '14 at 07:46
  • @DanielMartinus Log.e("Json String", jsonString); just logs the JSON string that is posted on the question in the top. It does not throw any exception, the Log.e("triplatitude", latitude); Log.e("triplongitude", longitude); does not show up in the logcat – kittu88 Dec 05 '14 at 07:48
  • you are trying to get string from latitude and longitude while infact they are not strings. – tony9099 Dec 05 '14 at 07:52

2 Answers2

1

I assume your json (in the json array) without escaping and with a little formatting looks like this:

[
 {
      "__type": "GeoPoint",
      "latitude": 51.165691,
      "longitude": 10.451526
  },
  {
      "__type": "GeoPoint",
      "latitude": 20.593684,
      "longitude": 78.96288
  }
]

I assume __type would work when you comment out latitude and longitude and insert: obj.getString("__type"); But you are now using obj.getString on latitude and longitude while they are not strings.

So use for latitude and longitude: (Edit: this is not necessary since the json parser will make it automatically a String)

obj.getDouble("latitude");

edit

I actually just tested your code and this worked:

String jsonString = " [{\n" +
            "      \"__type\": \"GeoPoint\",\n" +
            "      \"latitude\": 51.165691,\n" +
            "      \"longitude\": 10.451526\n" +
            "  },\n" +
            "  {\n" +
            "      \"__type\": \"GeoPoint\",\n" +
            "      \"latitude\": 20.593684,\n" +
            "      \"longitude\": 78.96288\n" +
            "  }]";

    JSONArray jsonarray;
    try {
        jsonarray = new JSONArray(jsonString);
        for(int j=0; j<jsonarray.length(); j++){
            JSONObject obj = jsonarray.getJSONObject(j);

            String latitude = obj.getString("latitude");
            String longitude = obj.getString("longitude");

            Log.e("triplatitude", latitude);
            Log.e("triplongitude", longitude);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Dion Segijn
  • 2,625
  • 4
  • 24
  • 41
  • No man, that is not showing the __type – kittu88 Dec 05 '14 at 07:56
  • See edit in my answer, only thing i changed is the jsonString. And i used the one from above the edit and used array prefix `[` `]` before the two objects. – Dion Segijn Dec 05 '14 at 08:04
  • String jsonString = arg0.get(i).get(0).getJSONArray("tripPoints").toString(); contains the JSON. What should I add before or after? – kittu88 Dec 05 '14 at 08:56
  • @kittu88 See my answer, you need to fix the raw JSON from the source. – jmn Dec 05 '14 at 09:07
  • @user32116 Thats excactly whats in my answer. @kittu88 you need to add `[` at the begin of the json String and `]` at the end of the json string. If you can't change the json string because its from an API try this http://stackoverflow.com/a/27188397/1164919 Since without `[` and `]` it's an JSONObject and not an `JSONArray`. did you try out my code in my answer here above? – Dion Segijn Dec 05 '14 at 09:15
  • @DanielMartinus I posted the answer before your edit, but anyways. It's not the `[]` that's the problem, it's the `"` characters. – jmn Dec 05 '14 at 09:21
  • I have added String jsonString = "["+arg0.get(i).get(0).getJSONArray("tripPoints").toString()+"]"; the resulting JSON is [["{\"__type:\"GeoPoint\",\"latitude\":51.165691,\"longitude\":10.451526}","{\"__type:\"GeoPoint\",\"latitude\":20.593684,\"longitude\":78.96288}"]] so it had basically added one extra box bracket at the beginning and end. – kittu88 Dec 05 '14 at 09:22
  • Then the json string is correct. Did you already try out my code on the bottom of my answer? I tested it and it should work. Just place it in an onCreate of an activity somewhere to easily test it. – Dion Segijn Dec 05 '14 at 09:24
  • @DanielMartinus http://jsonlint.com/ calls it a valid json. The previous one without the [] [ "{\"__type:\"GeoPoint\",\"latitude\":51.165691,\"longitude\":10.451526}", "{\"__type:\"GeoPoint\",\"latitude\":20.593684,\"longitude\":78.96288}" ] – kittu88 Dec 05 '14 at 09:25
  • again @kittu88 did you try out my code? that its valid json was already known. – Dion Segijn Dec 05 '14 at 09:27
  • @kittu88 Please comment on my original answer. You need to remove the `"` before `{` and after `}`. It will then say it's invalid due to the missing `"` after `__type`. – jmn Dec 05 '14 at 09:27
  • @DanielMartinus I did try it out, its not showing any result as it did earlier – kittu88 Dec 05 '14 at 09:29
  • @kittu88 sorry but if it ain't showing any results and you got no exception then your logcat is wrong i guess. Do you have it on `verbose`? Already tried debugging with breakpoints and checking the values? Or set a toast. `Toast.makeText(mContext, latitude + longitude, Toast.LENGTH_SHORT).show();` in the for loop – Dion Segijn Dec 05 '14 at 09:32
1

Your JSON array does not contain valid JSON objects. Removing the \ escape characters, you end up with this, which is not valid JSON:

[
    "{"__type:"GeoPoint","latitude":51.165691,"longitude":10.451526}",
    "{"__type:"GeoPoint","latitude":20.593684,"longitude":78.96288}"
]

Try fixing the JSON first and then see if this solves your issue. You can use JSONLint to make sure the JSON is valid.

Basically your JSON should look something like this:

[
    {
        "__type": "GeoPoint",
        "latitude": 51.165691,
        "longitude": 10.451526
    },
    {
        "__type": "GeoPoint",
        "latitude": 20.593684,
        "longitude": 78.96288
    }
]

EDIT 1

Seems like there's a bit of confusion. The issue is that the following is a string in JSON terms:

"{"__type:"GeoPoint","latitude":51.165691,"longitude":10.451526}"

We need an object, so we remove the " from the start and the end which turns it into the following:

{"__type:"GeoPoint","latitude":51.165691,"longitude":10.451526}

This is invalid JSON. What we need to do to fix this is add a " after __type. Now it looks like this:

{"__type":"GeoPoint","latitude":51.165691,"longitude":10.451526}

Finally it's valid. You need to find a way to fix the JSON at the source. What is the arg0 object and where does it get its data?

EDIT 2

If you can't fix the JSON at the source the following quick hack should work for this case:

jsonString = jsonString.replace("__type", "__type\"")
        .replace("\"{", "{")
        .replace("}\"", "}")
        .replace("\\\"", "\"");
jmn
  • 564
  • 5
  • 8
  • If you can then please post the suggested code about how to make the JSON valid and parse it. – kittu88 Dec 05 '14 at 09:30
  • First, where do you get the JSON from? It will need to be fixed at the source. The code is fine, just not the raw JSON. – jmn Dec 05 '14 at 09:32
  • It is generated from parse.com and its valid in the whole project. – kittu88 Dec 05 '14 at 09:33
  • Can you please post the value you get from `arg0.get(i).get(0)`? – jmn Dec 05 '14 at 09:53
  • removing .getJSONArray("tripPoints") ? – kittu88 Dec 05 '14 at 09:55
  • @DanielMartinus No, that's what's in `arg0.get(i).get(0).getJSONArray("tripPoints").toString();`. I'm trying to see the raw JSON before it's turned into a JSONArray. – jmn Dec 05 '14 at 10:02
  • I returns the json string that is posted on the top of the question. – kittu88 Dec 05 '14 at 10:04
  • @kittu88 Ok, but do you see why the actual JSON is invalid? If not, I suggest reading up more about the structure of JSON. – jmn Dec 05 '14 at 10:10
  • I have pasted the JSON in http://jsonlint.com/ and it says its a valid JSON – kittu88 Dec 05 '14 at 10:22
  • So can you suggest a regex or something to do the same? Nothing could be done in Parse database as the output is generated automatically – kittu88 Dec 05 '14 at 10:34
  • @kittu88 see 2nd edit – jmn Dec 05 '14 at 10:49
  • after fixing JSON what should be done? How will I parse it? – kittu88 Dec 05 '14 at 10:51
  • new json: [{"__type":"GeoPoint","latitude":7.873054,"longitude":80.771797},{"__type":"GeoPoint","latitude":71.706936,"longitude":-42.604303}] – kittu88 Dec 05 '14 at 10:53
  • @kittu88 Add the code in my 2nd edit after the following line: `String jsonString = arg0.get(i).get(0).getJSONArray("tripPoints").toString();`. Then run the code again and see what happens. – jmn Dec 05 '14 at 10:53