簡體   English   中英

Json解析-JAVA中的JSONArray到JSONObject

[英]Json parsing - JSONArray to JSONObject in 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

@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;
}

從Bean.java中的Sample.java中檢索json時 ,我得到了這種格式的輸出-

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

我想使用JsonSimple庫將其轉換為以下格式的JSONObject-

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

我只是一個初學者。 任何幫助,將不勝感激。 先感謝您。

您正在使用JSONArray實例化。 您需要使用JSONObject實例化

items=new JSONObject();

另外,您需要使用put方法而不是add方法

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

在這里查看更多

問題不是很清楚,但似乎您不想要Array。 當您顯式序列化為Array時,得到的輸出是Array。 如果您不希望使用Array,則使Java POJO保留所需的所有屬性並將其序列化。 []表示Json中的數組

示例可以做什么

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

並序列化此POJO類的Object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM