Java org.json.JSONObject能否生成{und";:[{value";:";some@one.com";}]}?
我正在尝试使用org.json.JSONObject构建以下目标json字符串:Java org.json.JSONObject能否生成{und";:[{value";:";some@one.com";}]}?,java,json,Java,Json,我正在尝试使用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"
{"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);
您可能想看看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);
您需要创建一个数组。非常感谢您的输入。您需要创建一个数组。非常感谢您的输入。