gpt4 book ai didi

java - org.json.JSONObject 可以生成 {"und":[ {"value" :"some@one.com"}]}?

转载 作者:太空宇宙 更新时间:2023-11-04 07:37:11 24 4
gpt4 key购买 nike

我正在尝试使用 org.json.JSONObject 构建以下目标 json 字符串:

{"und":[{"value":"some@one.com"}]} 

这是我的代码:

JSONObject und = new JSONObject();
und.accumulate("und", new JSONObject().put("value", "some@one.com"));
System.out.println( und.toString() );

但它会产生以下结果:

{"und":{"value":"some@one.com"}} 

如何生成目标json字符串?

感谢和问候。

编辑

感谢 SLAks 的输入,以下是生成目标字符串的代码:

     JSONObject und = new JSONObject();
JSONArray arr = new JSONArray();
und.put("und", arr);
arr.put(new JSONObject().put("value", "some@one.com"));
System.out.println( und.toString() );

最佳答案

您可能想看看 Jackson,它是 Java 上最高效且受支持的 JSON 库之一。

如果您熟悉解码/反序列化,您可以将 POJO 转换为 json,反之亦然。

@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class SomeBean {
Und[] und;
// TODO: Getters and setters

public static Und class {
public String value;
// TODO: Getters and setters
}
}

如果直接解析JSON字符串或文件,可以使用ObjectMapper类

SomeBean someBean = new ObjectMapper().readValue("input goes here", SomeBean.class);

// If you want just a string you can pass in the String class
String json = new ObjectMapper().readValue("input", String.class);

如果 JSON 来自 Web 服务,请查看 Spring 的 RestTemplate,它非常易于使用。

RestTemplate restTemplate = new RestTemplate();
SomeBean someBean = restTemplate.getForEntity("URI goes here", SomeBean.class);

String json = restTemplate.getForEntity("URI goes here", String.class);

关于java - org.json.JSONObject 可以生成 {"und":[ {"value" :"some@one.com"}]}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16674230/

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