【问题标题】:Json String created in Wrong Format以错误格式创建的 Json 字符串
【发布时间】:2016-05-24 07:31:44
【问题描述】:

我必须以 Http 请求的格式发送请求正文,格式如下:

 {
  "flag":false, 
  "Ids":["xyz","abc"]
}

我想:

    LinkedHashMap<String, Object> requestParamsMap = new LinkedHashMap<String, Object>();
    requestParamsMap.put("flag",false);

    ArrayList<String> IdList = new ArrayList<>();
    IdList.add("xyz");
    IdList.add("abc");
    requestParamsMap.put("Ids", IdList.toString());

然后我将 requestParamsMap 转换为 json 字符串。但我没有得到所需格式的请求正文。

我想创建一个可以以这种格式返回数据的通用方法,以便我可以在整个应用程序中使用它。

任何帮助将不胜感激.. !!!

【问题讨论】:

  • 显然你需要使用一些 json 序列化程序... LinkedHashMap.toString() 不会自动返回 json(ArrayList.toString() 都不会返回 json 数组)

标签: android json http android-networking


【解决方案1】:

做这样的事情:

 JSONObject object=new JSONObject();
    try {
        object.put("flag","xyz");
        JSONArray array=new JSONArray();
        array.put("xyz");
        array.put("abc");

        object.put("Ids",array);

        //added a log to see the output
        Log.e("output",object.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }

object.toString() 应该包含您想要的字符串格式的 json。您可以使用循环来填充 jsonArray 或 JSONObject 的内容,具体取决于您拥有的项目数

【讨论】:

    【解决方案2】:

    虽然根本不是这样,但您想要的输出是 JSONObject 中的 JSONArray 和另一个 JSONObject 中的 JSONObject。因此,您可以单独创建它们,然后可以将它们组合在一起。如下。

    代码

    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("root", jsonObject);
            Log.d("output", parent.toString(2));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

    输出

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

    【讨论】:

      猜你喜欢
      • 2014-04-24
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多