gpt4 book ai didi

java - 从 java 对象创建复杂的 JSON

转载 作者:行者123 更新时间:2023-12-01 10:21:13 33 4
gpt4 key购买 nike

这些是我的类(class)。

Class TypeC {

int var1;
HashMap<String,String>var2;
ArrayList<TypeC> var3;

}

Class TypeB {

TypeC var1;

}

Class TypeA {

Long var1;
TypeB var2;
}

我想创建TypeC的对象,然后将其转换为相应的JSON对象(复杂的JSON)。我尝试了以下方法,但不起作用。

    TypeC obj = new TypeC();
JSONObject TypeCJSON=new JSONObject(obj);

最佳答案

使用“com.fasterxml.jackson.databind.ObjectMapper”进行数据绑定(bind)的完整示例:

package spring.exos;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

public static void main(String[] args){

final Computer computer = new Computer();
computer.setBrand("Toshiba");
computer.setModel("TSB I7-SSD");
computer.setSpecs(new Specs(new Integer(256), new Integer(8), new Double(2.4)));

final ObjectMapper mapper = new ObjectMapper();
try {
System.out.println(mapper.writeValueAsString(computer));
} catch (JsonProcessingException e) {
e.printStackTrace();
}

}

public static class Computer{
private String brand;
private String model;
private Specs specs;

public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Specs getSpecs() {
return specs;
}
public void setSpecs(Specs specs) {
this.specs = specs;
}
}
public static class Specs {
private Integer hdd;
private Integer memory;
private Double cpu;

public Specs(Integer hdd, Integer memory, Double cpu) {
super();
this.hdd = hdd;
this.memory = memory;
this.cpu = cpu;
}
public Integer getHdd() {
return hdd;
}
public void setHdd(Integer hdd) {
this.hdd = hdd;
}
public Integer getMemory() {
return this.memory;
}
public void setMemory(Integer memory) {
this.memory = memory;
}
public Double getCpu() {
return cpu;
}
public void setCpu(Double cpu) {
this.cpu = cpu;
}
}
}

输出是:

{"brand":"Toshiba","model":"TSB I7-SSD","specs":{"hdd":256,"memory":8,"cpu":2.4}}

您需要依赖于:

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1-1</version>
</dependency>

关于java - 从 java 对象创建复杂的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35604150/

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