如何在Android中创建JSON格式的数据? [英] How to create JSON format data in android?

查看:107
本文介绍了如何在Android中创建JSON格式的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要传递一些参数的服务器,我需要通过如下 格式

I need to pass some parameters to server that i need to pass as below format

{
  "k2": {
    "mk1": "mv1",
    "mk2": [
      "lv1",
      "lv2"
    ]
  }
}

那么,怎样才能产生这种格式的机器人。

So how can generate this format in android.

我试图用这个<一href="http://$c$c.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_En$c$c_a_JSON_object">As例如5.3 中显示,但它是显示在 obj.writeJSONString(出)一个错误; 这条线。任何人都可以请解决这方面的帮助。

I tried this using the As shown in example 5.3 but it is showing a error at obj.writeJSONString(out); this line. Can anyone please help in solving this.

在此先感谢

推荐答案

它不是,虽然在所有的,你要输出JSONArray内的JSONObject和JSONObject的在另一个的JSONObject。所以,你可以单独创建它们,然后可以放一起。如以下

Its not that though at all, output you want is JSONArray inside JSONObject and JSONObject inside another JSONObject. So, you can create them seperately and then can put in together. as below.

try {
            JSONObject parent = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            jsonArray.put("lv1");
            jsonArray.put("lv2");

            jsonObject.put("mk1", "mv1");
            jsonObject.put("mk2", jsonArray);
            parent.put("k2", jsonObject);
            Log.d("output", parent.toString(2));
        } catch (JSONException e) {
            e.printStackTrace();
        }

输出 -

       {
           "k2": {
             "mk1": "mv1",
             "mk2": [
               "lv1",
               "lv2"
             ]
           }
         }

这篇关于如何在Android中创建JSON格式的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆