Home > other >  How to convert an json response that json array without key?
How to convert an json response that json array without key?

Time:10-04

I have a json reponse like given below.Basically,I want to convert an object and use it.

[
    {
        "Id": 1290,
        "N": "Türkiye",
        "Fid": 196,
        "EC": 10,
        "CL": null,
        "SID": 0
    },
    {
        "Id": 1239,
        "N": "Dünya",
        "Fid": 152,
        "EC": 63,
        "CL": null,
        "SID": 0
    }
]
 ... Goes on

Here is what I have tried,I am using org.json library.

String jsonString = response.body().string(); // Getting json response and converting to string.
JSONObject jsonResponse = new JSONObject( jsonString ); // Not working
JSONArray jsonArray = new JSONArray( jsonString ); // Not working
JSONArray matches = new JSONArray( jsonString ).getJSONArray(0); // Not working

But I am gettin those errors

A JSONObject text must begin with '{' at 0 [character 1 line 1]
A JSONArray text must begin with '{' at 0 [character 1 line 1]

I have checked topics like Parse JSON Array without Key. But the json described not like mine.

Any idea what should ı do?

CodePudding user response:

in Java you would first need to define a class which has all the attributes

public class MyClass {
    private int Id;
    private int N;
    private int Fid;
    private int EC;
    private int CL;
    private int Sid;

// getters, setters, no arg constructor
}

then you can use for example gson library to parse it like this:

MyClass[] myClassArray = gson.fromJson(jsonString , MyClass[].class)

CodePudding user response:

I really recommend you to use the Gson library it's way better to perform data operations:

public class User {
    int id;
    String n;
    int fid;
    int ec;
    String cl;
    int sid;

    public static User[] parse(String s){
        return new GsonBuilder().create().fromJson(s, User[].class);
    }
}

CodePudding user response:

Have you looked into Google's Gson? It is really easy to use and you can both serialize and deserialize objects.

Here is an example:

    public Company[] deserializeCompany() {
        Gson gson = new Gson();
        Company[] companies = gson.fromJson(companiesJSON, Company[].class);
        return companies;
    }

First you need to make a template class that has a member field for each key in the json. E.g. private String id for the 'Id' key in the json you provided. In my example it is the Company class.

Next you make a new Gson object using Gson gson = new Gson(); and use the .fromJson function supplying it both the Json array and the Object array type (which is of the form MyClass[].class).

  • Related