1

How can I get Java objects from this JSON string? We don't have the name of the object in the JSON string

[
    {
       "eqid": "c0001xgp",
       "magnitude": 8.8,
       "lng": 142.369,
       "src": "us",
       "datetime": "2011-03-11 04:46:23",
       "depth": 24.4,
       "lat": 38.322
  },
  {
       "eqid": "2007hear",
       "magnitude": 8.4,
       "lng": 101.3815,
       "src": "us",
       "datetime": "2007-09-12 09:10:26",
       "depth": 30,
       "lat": -4.5172
 }
]

I found a code like this to parse the JSON. JSONArray

earthquakes = json.getJSONArray("earthquakes");
 for(int i=0;i < earthquakes.length();i++){                      
        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject e = earthquakes.getJSONObject(i);
        map.put("id",  String.valueOf(i));
       map.put("name", "Earthquake name:" + e.getString("eqid"));
       map.put("magnitude", "Magnitude: " +     e.getString("magnitude"));
       mylist.add(map);
   }

But it is just in case we have object name :"earthquake" like this

{"earthquakes":[

    {
       "eqid": "c0001xgp",
       "magnitude": 8.8,
       "lng": 142.369,
       "src": "us",
       "datetime": "2011-03-11 04:46:23",
       "depth": 24.4,
       "lat": 38.322
  },
  {
       "eqid": "2007hear",
       "magnitude": 8.4,
       "lng": 101.3815,
       "src": "us",
       "datetime": "2007-09-12 09:10:26",
       "depth": 30,
       "lat": -4.5172
 }
]}

What should I do if I don't have the name "earthquake". Sorry I cannot add new answer to myself, so I just edit the question.

1

1 Answer 1

1

You could use a JSON parser library like google-json which will allow you to parse this JSON into a strongly typed Java class which you must define. In this case you will define a Java class with properties such as eqid, magnitude, ... and then the parser will return you an array of this object.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I found a code like this to parse the JSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.