简体   繁体   中英

How to transform a JSONarray to a JSONObject in Java

I know this has been asked a lot but i really can't find any working solution.

I am requesting an API and if i print the parameter

String result = api.Request();
System.out.println(result);

The respose is in the following form:

    [
        [ Jon, Doe , 18 , 18],
        [ Jon, Doe , 18 , 18],
        [ Jon, Doe , 18 , 18]
    ]

At the moment a working solution i have is

   JSONArray arr = new JSONArray(result);
   User user = new User(arr.getJSONArray(i).get(j).....)
   You get the point
    Class User
    {
       public String name;
       public String lastName;
       public int num;
       public int numb;
      //getters setters
    }

I want to use gson or something else to tranform my JSONArray to a Java object.

     User[] user = new Gson().fromJson(result,User[].class);
     expected BEGIN_OBJECT but was BEGIN_ARRAY

Any help is appreciated.

First thing I don't know is how one can define a class like this Class User() {} .

You can use this class com.fasterxml.jackson.databind.ObjectMapper to convert a reference to a JSON, and you can pass a List<User> to get the JSON array

public static String asJsonString(final Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e) {
        System.out.println("Cannot convert to JSON");
    }
}

This is a sample main method

public static void main(String[] args) {
    System.out.println(asJsonString(new User("John", "Doe", 100, 200)));
    
    User user1 = new User("John", "Doe", 100, 200);
    User user2 = new User("John", "Snow", 200, 300);
    User user3 = new User("John", "Pit", 300, 400);
    
    List<User> list = new ArrayList<User>();
    list.add(user1);
    list.add(user2);
    list.add(user3);
    
    System.out.println(asJsonString(list));
}

This will be the respective output

{"name":"John","lastName":"Doe","num":100,"numb":200}
[{"name":"John","lastName":"Doe","num":100,"numb":200},{"name":"John","lastName":"Snow","num":200,"numb":300},{"name":"John","lastName":"Pit","num":300,"numb":400}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM