如何解析复杂的Json数组

时间:2014-08-22 08:16:33

标签: android

如何以json格式输入。

{
    "caller-id": "2434141414",
    "map-id": "2",
    "src": {
        "x": "23",
        "y": "34"
    },
    "dest": {
        "x": "23",
        "y": "34"
    }
}

我试过这样:

JSONObject src = new JSONObject();
        JSONObject dest = new JSONObject();
        src.put("src", mObjUserPath.get("x1"));
        src.put("src", mObjUserPath.get("y1"));
        dest.put("dest", mObjUserPath.get("x2"));
        dest.put("dest", mObjUserPath.get("y2"));
        json.put("caller-id", Util.getDeviceID(this));
        json.put("map-id", RestClientAsyncTask.mapId);
        json.put("src", src);
        json.put("dest", dest);

但格式不符合我的预期。请帮助 任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

请按照此示例尝试一下:

{ <br>
    "version": "1.0.0",<br>

    "datastreams": [

        {
            "id": "example",
            "current_value": "333"
        },

        {
            "id": "key",
            "current_value": "value"

        },

        {
            "id": "datastream",
            "current_value": "1337"

        }
    ]
}

    JSONObject Parent = new JSONObject();
    JSONArray array = new JSONArray();

    for (int i = 0 ; i < datastreamList.size() ; i++)
    {
        JSONObject jsonObj = new JSONObject();

        jsonObj.put("id", datastreamList.get(i).GetId());
        jsonObj.put("current_value", datastreamList.get(i).GetCurrentValue());
        array.put(jsonObj);
    }       
    Parent.put("datastreams", array);       
    Parent.put("version", version);

发送

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    StringEntity se = new StringEntity( Parent.toString());  
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");
    post.setEntity(se);
    client.execute(post);

答案 1 :(得分:0)

这是解决这个问题的方法。

JSONObject json = new JSONObject();
    try {


    JSONObject obj_src = new JSONObject();
    obj_src.put("x", mObjUserPath.get("x1"));
    obj_src.put("y", mObjUserPath.get("y1"));

    JSONObject obj_dest = new JSONObject();
    obj_dest.put("x", mObjUserPath.get("x2"));
    obj_dest.put("y", mObjUserPath.get("y2"));

    json.put("caller-id", "123);
    json.put("map-id", "0"));
    json.put("src", obj_src);
    json.put("dest", obj_dest);