【问题标题】:Json parsing - JSONArray to JSONObject in JAVAJson 解析 - JAVA 中的 JSONArray 到 JSONObject
【发布时间】:2017-01-12 07:10:32
【问题描述】:

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

我只是一个初学者。任何帮助,将不胜感激。提前谢谢你。

【问题讨论】:

  • 您制作了一组对象,但您需要 1 个具有属性的对象。
  • 你没有在这里展示什么是 Sample.java。如果 Sample.java 负责打印一个示例项目,您可能只需从 JSONArray 中获取第一个项目并打印它。

标签: java json json-simple


【解决方案1】:

您正在使用 JSONArray 进行实例化。你需要用 JSONObject 实例化

items=new JSONObject();

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

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

See more here

【讨论】:

    【解决方案2】:

    这个问题不是很清楚,但似乎你不想要一个 Array 。 当您显式序列化为 Array 时,您得到的输出是一个 Array 。如果您不想要一个数组,那么制作一个 Java POJO 来保存所有需要的属性并将其序列化。 [ ] 表示 Json 中的一个数组

    举例说明可以做什么

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

    并序列化这个 POJO 类的一个对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多