本文介绍了从Java对象创建复杂的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这些是我的课程.
Class TypeC {
int var1;
HashMap<String,String>var2;
ArrayList<TypeC> var3;
}
Class TypeB {
TypeC var1;
}
Class TypeA {
Long var1;
TypeB var2;
}
我想创建TypeC对象,然后将其转换为相应的JSON对象(复杂JSON).我尝试了以下操作,但不起作用.
I want to create object of TypeC and then convert it into a corresponding JSON object (complex JSON).I tried the following but it doesnt work.
TypeC obj = new TypeC();
JSONObject TypeCJSON=new JSONObject(obj);
推荐答案
使用'com.fasterxml.jackson.databind.ObjectMapper'进行数据绑定的完整示例:
A full example of data binding using '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;
}
}
}
输出为:
您需要具有以下依赖性:
You need to have a dependency to:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1-1</version>
</dependency>
这篇关于从Java对象创建复杂的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!