2 回答
TA贡献1921条经验 获得超9个赞
使用Jackson 的POJO 和ObjectMapper :
public class Data {
private final String name;
private final String id;
private final List<String> mailId;
private final List<Opwarden> bundle1;
public Data(final String name, final String id, final List<String> mailId, final List<Opwarden> bundle1) {
this.name = name;
this.id = id;
this.mailId = mailId;
this.bundle1 = bundle1;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public List<String> getMailId() {
return mailId;
}
public List<Opwarden> getBundle1() {
return bundle1;
}
}
和欧普华登:
public class Opwarden {
private final String number;
private final String title;
public Opwarden(final String number, final String title) {
this.number = number;
this.title = title;
}
public String getNumber() {
return number;
}
public String getTitle() {
return title;
}
}
您可以使用以下方法创建 JSON:
ObjectMapper objectMapper = new ObjectMapper();
Data data = new Data("xyz", "428", List.of("mailme@mail.com"), List.of(new Opwarden("132344345", "title")));
System.out.println(objectMapper.writeValueAsString(data));
输出:
{
"name": "xyz",
"id": "428",
"mailId": [
"mailme@mail.com"
],
"bundle1": [
{
"number": "132344345",
"title": "title"
}
]
}
TA贡献1865条经验 获得超7个赞
我建议使用 JACKSON 对象映射器。如果您不想重新创建上述模型结构,请编写 pojo。
可以在这里找到一个很好的教程在这里输入链接描述
你基本上是这样使用它的:
ObjectMapper objectMapper = new ObjectMapper(); String jsonRepresentation = objectMapper.writeValueAsString( anyObject );
如上所述,anyObject 也可以是映射键/值,值也可以再次映射。
您的具体用例将是这样的:
ObjectMapper m = new ObjectMapper();
Map<String, Object> input = new HashMap<String, Object>();
input.put( "name", "xyz" );
input.put( "id", "428" );
input.put( "mailId", new String[] { "mailme@mail.com" } );
Map<String, Object> opwarden = new HashMap<String, Object>();
opwarden.put( "number", "132344345" );
opwarden.put( "title", "title" );
Map<String, Object> bundle1 = new HashMap<String, Object>();
bundle1.put( "opwarden", opwarden );
input.put( "bundle1" , bundle1 );
String json = m.writeValueAsString( input );
添加回答
举报