繁体   English   中英

我怎样才能创建一个新的元素/节点,然后向它添加一个新的键和值?

[英]How can I create a new element/node and then add a new key and value to it?

我有以下代码:

import org.json.JSONObject;
import org.json.XML;
public class Xml2Json {

public static void main(String[] args) {
    
    String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
    JSONObject jsonObject = XML.toJSONObject(xmlString);
    
    jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
    
    jsonObject.getJSONObject("users").append("marks",23); }
}

它产生如下所示的 output:

{"users":{"report":{"sub":"eng","score":30},"marks":[23],"user":{"name":"test1"}}}

但是我需要向users添加一个新元素newUser ,并且标记应该在newUser内,就像:

{"users":{"report":{"sub":"eng","score":30},"newUser":{"marks":{23}},"user":{"name":"test1"}}}

有人可以帮我吗?

而不是您的代码使用下面提到的代码:

public static void main(String[] args) throws JSONException {

    String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
    JSONObject jsonObject = XML.toJSONObject(xmlString);

    jsonObject.getJSONObject("users").getJSONObject("user").remove("age");

    Map<String, int[]> marks = new HashMap<>();
    marks.put("marks", new int[]{23});
    jsonObject.getJSONObject("users").put("newUser", marks);
    System.out.println(jsonObject);
}

其中行jsonObject.getJSONObject("users").put("newUser", marks); 将添加具有相应映射标记的新key(newUser)为 Map object。

没有 Map 和 HashMap:

public static void main(String[] args) throws JSONException {

        String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
        JSONObject jsonObject = XML.toJSONObject(xmlString);

        jsonObject.getJSONObject("users").getJSONObject("user").remove("age");

        JSONObject marksJSONObject = new JSONObject();
        marksJSONObject.put("marks",new int[]{23});
        jsonObject.getJSONObject("users").put("newUser", marksJSONObject);
        System.out.println(jsonObject);
    }

OUTPUT:

{"users":{"newUser":{"marks":[23]},"report":{"sub":"eng","score":30},"user":{"name":"test1"}}}
    String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
    JSONObject jsonObject = XML.toJSONObject(xmlString);
    
    jsonObject.getJSONObject("users").getJSONObject("user").remove("age");

    JSONObject newUser = new JSONObject();
    
    newUser.put("marks", 32);

    jsonObject.put("newUser", newUser);

暂无
暂无

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

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