简体   繁体   English

Json解析-JAVA中的JSONArray到JSONObject

[英]Json parsing - JSONArray to JSONObject in JAVA

Item.java Item.java

JSONObject json = new JSONObject();
private String value;
private String type;
public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

public String getType() {
    return type;
}

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

public String toString() {
    json.put(value, type);
    return json.toString();
  }

Bean.java Bean.java

@PostConstruct
public void init() {
    items=new JSONArray();
}


public void add() throws ParseException {   
    items.add(new Item());   
}

public void remove(Item item) {
    items.remove(item);
}

public void save() {
    System.out.println("JsonSchema "+items);
}

public JSONArray getItems() {  
    return items;
}

While retrieving json from Sample.java in Bean.java - I get the output of this format - 从Bean.java中的Sample.java中检索json时 ,我得到了这种格式的输出-

[{"id":"number"},{"name":"text"},{"type":"number"}]

I want to convert this to JSONObject of below format using JsonSimple library- 我想使用JsonSimple库将其转换为以下格式的JSONObject-

{"id":"number","name":"text","type":"number"} //convert to this format

I am just a beginner. 我只是一个初学者。 Any help would be appreciated. 任何帮助,将不胜感激。 Thank you in advance. 先感谢您。

You are instantiating with JSONArray. 您正在使用JSONArray实例化。 You need to instantiate with JSONObject 您需要使用JSONObject实例化

items=new JSONObject();

Also you need to use the put method instead of add method 另外,您需要使用put方法而不是add方法

items.put("item1", new item()); 

See more here 在这里查看更多

The question is not very clear but it seems you dont want an Array . 问题不是很清楚,但似乎您不想要Array。 The output you are getting is an Array as you are explicitly serializing into an Array . 当您显式序列化为Array时,得到的输出是Array。 If you dont want an Array then make a Java POJO to hold all the attributes needed and serialize that. 如果您不希望使用Array,则使Java POJO保留所需的所有属性并将其序列化。 [ ] represents an array in Json []表示Json中的数组

Example what could be done 示例可以做什么

class POJO {
attribute 1;
attribute 2;
attribute 3;
}

and serialize an Object of this POJO class 并序列化此POJO类的Object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM