这些是我的课程。
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);
答案 0 :(得分:1)
使用'com.fasterxml.jackson.databind.ObjectMapper'进行数据绑定的完整示例:
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>
答案 1 :(得分:0)
如果您愿意使用其他库,请使用Gson https://github.com/google/gson,您只需要这样做:
<itemizedlist role="type6" id="ecls_bio_becls_a3_a43205230.SL2392155.512">