lovesunset
lovesunset

Reputation: 21

How to get Java objects from JSON string

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.

Upvotes: 1

Views: 1751

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 1

Related Questions