gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:57 24 4
gpt4 key购买 nike

我有一个像这样的 Json 数组

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

到目前为止我已经做到了

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

我的汽车级别是

  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; }
}

但它不起作用。如何将此字符串数组转换为 Java 数组?以及如何使用键检索元素?

最佳答案

首先,您的源 Json 不正确。

内部数组应更改为对象,因为数组不是结构,而且这些内部对象应映射到Car对象。

因此,请像这样更改您的 json 字符串:

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

然后这些内部对象将被映射到 Java 中的 Car 对象,使用以下代码:

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

然后要读取汽车数组数据,您可以使用:

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());
}

这就是您的 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;
}
}

关于java - 在 Spring MVC 中使用 Gson 将嵌套 Json 数组转换为 Java 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48880269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com