简体   繁体   English

如何在 Java 中将 JSONarray 转换为 JSONObject

[英]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我正在请求 API,如果我打印参数

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.我想使用 gson 或其他东西将我的 JSONArray 转换为 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() {} .我不知道的第一件事是如何定义一个 class 这样的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您可以使用此 class com.fasterxml.jackson.databind.ObjectMapper将引用转换为 JSON,您可以传递一个List<User>来获取 JSON 数组

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这将是各自的 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}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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