gpt4 book ai didi

java - Java 中的多个数组和对象 JSON

转载 作者:行者123 更新时间:2023-12-02 01:37:52 25 4
gpt4 key购买 nike

我正在尝试创建此 json 格式,以便我可以使用不同的值测试此请求,但问题是在 java 中创建此 json 格式对我来说很困难。

正如您所看到的,我正在使用 java 并使用 JSONObject 类,然后分配一个键及其值来创建这种格式。但看起来这是一个错误的方法。

{
"to": "918892******",
"type": "contacts",
"contacts": [{
"addresses": [{
"city": "bangalore",
"country": "India",
"country_code": "91",
"state": "----",
"street": "** Main",
"type": "Home",
"zip": "000000"
}],
"birthday": "08-09-1994",
"emails": [{
"email": "*******bhit9@gmail.com",
"type": "Email"
}],
"ims": [],
"name": {
"first_name": "Sobhit",
"formatted_name": "l",
"last_name": "Sharma"
},
"org": {
"company": "------"
},
"phones": [{
"phone": "890464----",
"type": "Work"
}],
"urls": []
}],
"callback": "{{callback}}"
}

我要创建的代码是

public void ContactJson(){
JSONObject jsonObj = new JSONObject();
JSONObject pairKey = new JSONObject();
JSONArray arrayMain = new JSONArray();
JSONObject Array_itemMain = new JSONObject();
pairKey.put("first_name","first_name");
pairKey.put("formatted_name","formatted_name");
pairKey.put("last_name","last_name");
jsonObj.put("to", "To");
jsonObj.put("type","type");
jsonObj.put("contacts", arrayMain,pairKey);
Array_itemMain.put("addresses","addresses");
Array_itemMain.put("birthday","08-09-1994");
Array_itemMain.put("emails","*****@gmail.com");
Array_itemMain.put("ims","null");
Array_itemMain.put("name","sobhit");
Array_itemMain.put("org","addresses");
Array_itemMain.put("Phones","*****");
Array_itemMain.put("urls","url");
jsonObj.put("callback","Calbback");
arrayMain.add(Array_itemMain);
CreatedJson = jsonObj.toString();
System.out.println(CreatedJson);
}

当我创建多个 json 数组并分配给主数组时,问题就开始了,它显示错误,因为它只在主 json 主体中使用一个数组。不知道如何实现这一目标,但任何帮助都会非常感激。

最佳答案

您可以按照所需的结构生成 POJO 类,然后使用使用所需值生成的类实例化对象,然后在请求中使用该对象。

您可以使用类似 this 的内容从 json 结构生成 POJO。

示例:

 public class Test {
private String to;
private String type;
ArrayList < Object > contacts = new ArrayList < Object > ();
private String callback;


// Getter Methods

public String getTo() {
return to;
}

public String getType() {
return type;
}

public String getCallback() {
return callback;
}

// Setter Methods

public void setTo(String to) {
this.to = to;
}

public void setType(String type) {
this.type = type;
}

public void setCallback(String callback) {
this.callback = callback;
}
}

使用上述内容创建类后,请按如下所示实例化:

Test request = new Test();
request.setTo("TestString");
request.setType("TestSting");

为了简洁起见,我只给出了一些小例子。我希望你能明白。

如果您不想手动设置所有字段的值,您甚至可以使用 Jackson 的 ObjectMapper 将 json 作为字符串映射到您创建的 POJO 类。

关于java - Java 中的多个数组和对象 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54956258/

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