当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How to parse the Object in JSON type

问题描述:

I have a JSON file and I do not know how can I parse the part of "coordinates", others done already. It seems null, others seem ok when I try to reach them. I guess, coordinates part is another class defined in cities part. Could you please help me to get coordinates of cities?

I kept my cities in a linkedlist.

 "cities" : [

{

"code" : "SCL" ,

"name" : "Santiago" ,

"country" : "CL" ,

"continent" : "South America" ,

"timezone" : -4 ,

"coordinates" : {"S" : 33, "W" : 71} ,

"population" : 6000000 ,

"region" : 1

}

static List<City> allCities = new LinkedList<City>();

static List<Flight> allFlights = new LinkedList<Flight>();

static JSONArray cities;

static JSONArray flights;

FileReader reader = new FileReader("csair.json");

JSONObject CSAirData = (JSONObject) JSONValue.parse(reader);

cities = (JSONArray) CSAirData.get("cities");

flights = (JSONArray) CSAirData.get("routes");

网友答案:

Assuming "cities" is an attribute of variable myVar, like this

var myVar = {
  "cities": [
    {
      "code": "SCL",
      "name": "Santiago",
      ...
    }
  ]
};

then you could access "coordinates" by doing

myVar.cities[0].coordinates
  • "cities" corresponds to an array
  • the first element in the array (index = 0) is an object
  • that object has an attribute called "coordinates", which references another object

Edit

Now that I see you are using Java code, you just need to transform this syntax into Java.

We know that "cities" is a JSONArray.

JSONObject city = cities.get(0);  // Get the first city in the array (index = 0)
JSONObject coordinates = city.getJSONObject("coordinates");
int coordinates_s = coordinates.getInt("S");
int coordinates_w = coordinates.getInt("W");
分享给朋友:
您可能感兴趣的文章:
随机阅读: