![](/img/trans.png)
[英]Need to present the nodes of a binary search tree through an array in Java. How do I do that?
[英]I need to create json object in java. How will I do it?
[{
id: 12345, //Id given by android app
name: Name,
status: {
yes: [N1, n2, n3],
no: [n1, n2 ,n3]
}
}]
我将如何在 Java 中为此编写 json 对象?
我的尝试:
JSONObject object=new JSONObject();
JSONArray jsonarray=new JSONArray();
try {
object.put("id",12345);
object.put("name",Name);
jsonarray.put("yes");
jsonarray.put("no");
} catch (JSONException js) {
js.printStackTrace();
}
我认为问题出在 jsonarray 上。 我需要再次编写 jsonarray 对象。 但我无法弄清楚我将如何做到这一点。
编辑
这个问题不重复。
@ShaishavJogani 我不认为这个问题是你提供链接的问题的重复,因为这个问题是关于生成 JSON 而这是关于解析 JSON。
status
也是一个JSONObject
, yes
和no
是JSONArray
类型的这个JSONObject
的属性,主要对象在JSONArray
,所以我会这样做:
JSONObject object = new JSONObject();
object.put("id", 12345);
object.put("name", "Name");
JSONObject status = new JSONObject();
object.put("status", status);
status.put("yes", new JSONArray(Arrays.asList("N1", "n2", "n3")));
status.put("no", new JSONArray(Arrays.asList("n1", "n2", "n3")));
JSONArray array = new JSONArray(Collections.singletonList(object));
System.out.println(array);
输出:
[{"name":"Name","id":12345,"status":{"no":["n1","n2","n3"],"yes":["N1","n2","n3"]}}]
我希望在数组之前会有一个 JSONObject 或者可能是数组的一些名称:如果这个数组出现在 JSONObject 中,请尝试下面的代码:
try {
JSONObject object=new JSONObject();
JSONArray jsonarray=object.getJSONArray();
if(jsonarray.length()>0)
{
for(int i=0; i<jsonarray.length();i++)
{
object.put("id",12345);
object.put("name",Name);
jsonarray.put("yes");
jsonarray.put("no);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
除此以外:
try {
JSONArray jsonarray=new JSONArray("Name of Array");
if(jsonarray.length()>0)
{
for(int i=0; i<jsonarray.length();i++)
{
object.put("id",12345);
object.put("name",Name);
jsonarray.put("yes");
jsonarray.put("no);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.