简体   繁体   English

在Spring MVC中使用Gson将嵌套的Json数组转换为Java数组

[英]Convert a Nested Json Array to Java Array Using Gson In Spring MVC

I have a Json array like this 我有一个像这样的Json数组

String carJson = "[{ \\"brand\\" : \\"Mercedes\\", \\"doors\\" : 5 }, { \\"brand\\" : \\"Mercedes\\", \\"doors\\" : 5 }]"; 字符串carJson =“ [{\\” brand \\“:\\”梅赛德斯\\“,\\”门\\“:5},{\\” brand \\“:\\”梅赛德斯\\“,\\”门\\“:5}]” ;

so far i have done this 到目前为止,我已经做到了

Car cars = gson.fromJson(carJson,Car[].class);

and my car class is 我的车课是

  private static class Car {
            private String brand = null;
            private int doors = 0;

            public String getBrand() { return this.brand; }
            public void   setBrand(String brand){ this.brand = brand;}

            public int  getDoors() { return this.doors; }
            public void setDoors (int doors) { this.doors = doors; }
    }

But its not working. 但是它不起作用。 How can I convert this string array to Java array? 如何将该字符串数组转换为Java数组? And how to retrieve the elements using the keys? 以及如何使用键检索元素?

First of all your source Json is incorrect. 首先,您的来源Json不正确。

The internal arrays should be changed to objects , because arrays aren't a key and value structure, and because these internal objects should be mapped to Car objects. 内部arrays应改为objects ,因为arrays是不是一个keyvalue的结构,并且因为这些内部objects应该被映射到Car对象。

So change your json string like this: 因此,像这样更改您的json字符串:

String carJson = "[{ \"brand\" : \"Mercedes\", \"doors\" : 5 }, { \"brand\" : \"Mercedes\", \"doors\" : 5 }]";

Then these internal objects will be mapped to Car objects in Java, using this code: 然后,使用以下代码将这些内部对象映射到Java中的Car对象:

Car[] cars = gson.fromJson(carJson, Car[].class);

Then to read the cars array data, you can use: 然后,要读取汽车数组数据,可以使用:

for(int i=0; i<cars.length; i++){
    Car c = cars[i];
    System.out.println("Car "+ i +" is : Brand= "+ c.getBrand() + "and doors = "+c.getDoors());
}

And this is how should be your Car class defined: 这是应该如何定义Car类:

public class Car {
    private String brand;
    private int doors;

    //Constructors

    public String getBrand(){
       return this.brand;
    }

    public void setBrand(String b){
       this.brand = b;
    }

    public String getDoors(){
       return this.doors;
    }

    public void setDoors(int n){
       this.doors= n;
    }
}

Fix your json: 修复您的json:

String carJson ="[{ \"brand\" : \"Mercedes\", \"doors\" : 5 }, { \"brand\" : \"Mercedes\", \"doors\" : 5 }]";

And then you can do: 然后您可以执行以下操作:

Car cars[] = new Gson().fromJson(carJson, Car[].class);

class Car {
    private String brand;
    private int doors;
}

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

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