0

I have this JSON file called city.list.json, containing objects like these:

{
"id": 707860,
"name": "Hurzuf",
"country": "UA",
"coord": {
  "lon": 34.283333,
  "lat": 44.549999
}}

How can I put name's value into array?

This is the code I've tried:

String name = null;

    JSONArray jsonArr = new JSONArray("[JSON String]");
    ArrayList<Data> dataList = new ArrayList<>();
    for (int i = 0; i < jsonArr.length(); i++) {

        JSONObject jsonObj = jsonArr.getJSONObject(i);
        Data data = new Data();

        data.name = jsonObj.getString("name");


        dataList.add(data);
    }

But it gives me errors on data saying "Constructor Data in class Data cannot applied to given types"

1

1 Answer 1

-1

You can use GSON library to achieve this task:

String input = yourSampleJson;
Gson gson = new Gson();
Map<String,Object> inputPojo = new HashMap<>();
inputPojo = gson.fromJson(input, inputPojo.class); // This map now contains the representation of your JSON.

I generally prefer having a POJO class which represents your JSON structure something as :

Class DanielePojo {
  Integer id;
  String name;
  String country;
  Coord coord; // This is another class similar to this POJO which is represented as Object in your JSON
 // Then your getters and setters
}

Then you can convert JSON into Pojo object directly without having a MAP as an intermediate object.

DanielePojo pojo = new GSON.fromJSON(input,DanielePojo.class); 
Sign up to request clarification or add additional context in comments.

Comments

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.