简体   繁体   English

如何将JSONObject的元素转换为单个元素数组?

[英]How would I convert an element of a JSONObject to a single element array?

I am using org.json.JSONObject and have a json object defined that was converted from XML. 我正在使用org.json.JSONObject并定义了一个从XML转换而来的json对象。 I want to be able to convert one of the elements of the JSON to a single element array, but am unclear on how to do this. 我希望能够将JSON的元素之一转换为单个元素数组,但是尚不清楚如何执行此操作。 For example, say I have the following json: 例如,说我有以下json:

{
    "heading": "value",
    "numbers": [1,2,3],
    "onevalarray": "MyVal"
}

stored in an org.json.JSONObject object. 存储在org.json.JSONObject对象中。 However, I want the element "onevalarray" to be a single element array: 但是,我希望元素“ onevalarray”是单个元素数组:

{
    "heading": "value",
    "numbers": [1,2,3],
    "onevalarray": ["MyVal"]
}

How would I accomplish this? 我将如何完成?

Call the method getJsonArray in the JSONbject object and specify the name of the property in the JSONObject which has the JSONArray in it like this: 在JSONbject对象中调用方法getJsonArray,并在其中包含JSONArray的JSONObject中指定属性的名称,如下所示:

Imagine that myJsonObject has this: 假设myJsonObject具有以下内容:

{"heading": "value", "numbers": [1,2,3], "onevalarray": "MyVal"}

And you want a JSONArray with onevalarray data. 而且您想要一个带有onevalarray数据的JSONArray。 Try it: 试试吧:

 JSONArray jsonArray = myJsonObject.getJSONArray("onevalarray");

Once you have the value of the onevalarray in the onevalarray JSONArray then remove the onevalarray in the original array and the put it again in this way: 在onevalarray JSONArray中获得onevalarray的值后,请删除原始数组中的onevalarray并以这种方式再次放置它:

myJsonObject.remove("onevalarray");

myJsonObject.put("onevalarray", jsonArray);

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

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