【问题标题】:JSONArray to String in javaJava中的JSONArray到String
【发布时间】:2014-11-06 09:47:18
【问题描述】:

我有一个JSONArray,看起来像这样:

如何将其转换为字符串?

如果我尝试:

json.toString();

字符串是:

["package.package.ChecklistModels.ChecklistAnswer@405dddd8","package.package.ChecklistModels.ChecklistAnswer@405ddf48","package.package.ChecklistModels.ChecklistAnswer@405de070","package.package.ChecklistModels.ChecklistAnswer@405de198","package.package.ChecklistModels.ChecklistAnswer@405de2c0","package.package.ChecklistModels.ChecklistAnswer@405de3e8","package.package.ChecklistModels.ChecklistAnswer@405de510"]

但我想要这样的东西:

    {
 "json": 
    "values": [
        {
            "answer": "true",
            "remark":"",
            "questionId": "0"
            "checklistId": "2"
        },
        {
            "answer": "true",
            "remark":"",
            "questionId": "0"
            "checklistId": "2"
        }
    ]
}

编辑:

这是我如何制作 json 数组的片段:

   if(cb.isChecked() || !text.getText().toString().equals("")){
                    ChecklistAnswer answer = new ChecklistAnswer(questions.get(id).id, 2, cb.isChecked(), text.getText().toString());

                    answers.add(answer);
                }
            }
            JSONArray json = new JSONArray(answers);
            String jsonString = json.toString();

【问题讨论】:

  • 显示一些你的代码的sn-p
  • 它按预期工作...您只需将 ChecklistAnswer 对象放入数组中...而不是 JSONObject ...ChecklistAnswer.toString() 返回 "xx.xx.xx.ChecklistAnswer@XXX" 。 .. 所以要么重写 ChecklistAnswer.toString 方法以返回 json 字符串,要么创建一个函数将 ChecklistAnswer 转换为 JSOObject
  • 显示用于json解析的代码
  • 我添加了一些代码@CapDroid
  • 而不是 answers.add(answer); 使用 answers.add(answer.toJSONObject()); (是的,你必须自己在 ChecklistAnswer 中编写 toJSONObject 方法 - 这应该很简单 - 就像将所有 ChecklistAnswer 的属性放入新的JSON对象)

标签: java android arrays json string


【解决方案1】:

问题不在于 @Selvin 提到的 JSONArray.toString()。

来自 JSONArray 来源:

/**
 * Encodes this array as a compact JSON string, such as:
 * <pre>[94043,90210]</pre>
 */
@Override public String toString() {
    try {
        JSONStringer stringer = new JSONStringer();
        writeTo(stringer);
        return stringer.toString();
    } catch (JSONException e) {
        return null;
    }
}

/**
 * Encodes this array as a human readable JSON string for debugging, such
 * as:
 * <pre>
 * [
 *     94043,
 *     90210
 * ]</pre>
 *
 * @param indentSpaces the number of spaces to indent for each level of
 *     nesting.
 */
public String toString(int indentSpaces) throws JSONException {
    JSONStringer stringer = new JSONStringer(indentSpaces);
    writeTo(stringer);
    return stringer.toString();
}

问题是您需要先将您的 ChecklistAnswer 转换为 JSON 对象才能使您的 JSONArray 正常工作。

再次来自 Javadoc:

/**
 * A dense indexed sequence of values. Values may be any mix of
 * {@link JSONObject JSONObjects}, other {@link JSONArray JSONArrays}, Strings,
 * Booleans, Integers, Longs, Doubles, {@code null} or {@link JSONObject#NULL}.
 * Values may not be {@link Double#isNaN() NaNs}, {@link Double#isInfinite()
 * infinities}, or of any type not listed here.

...

【讨论】:

    【解决方案2】:

    在我的 ChecklistAnwer 课程中我添加了:

       public JSONObject toJsonObject(){
        JSONObject json = new JSONObject();
    
        try {
            json.put("questionId", questionId);
            json.put("checklistId", checklistId);
            json.put("answer", answer);
            json.put("remark", remark);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
        return json;
    }
    

    在我的其他班级:

    JSONArray answers = new JSONArray();
    
    ChecklistAnswer answer = new ChecklistAnswer(questions.get(id).id, 2, cb.isChecked(),         text.getText().toString());
    
    answers.put(answer.toJsonObject());
    

    如果我填充了数组:

    String js = answers.toString(1);
    

    然后返回:

    [
     {
      "answer": true,
      "questionId": 1,
      "remark": "",
      "checklistId": 2
     },
     {
      "answer": false,
      "questionId": 4,
      "remark": "teesxfgtfghyfj",
      "checklistId": 2
     },
     {
      "answer": true,
      "questionId": 4,
      "remark": "",
      "checklistId": 2
     },
     {
      "answer": true,
      "questionId": 4,
      "remark": "",
      "checklistId": 2
     },
     {
      "answer": true,
      "questionId": 4,
      "remark": "",
      "checklistId": 2
     },
     {
      "answer": true,
      "questionId": 4,
      "remark": "",
      "checklistId": 2
     },
     {
      "answer": true,
      "questionId": 4,
      "remark": "",
      "checklistId": 2
     }
    ]
    

    感谢@Selvin

    【讨论】:

      【解决方案3】:

      您不需要使用任何额外的库。 JSONArray 类有 an extra .toString(int) method 可以为您完成漂亮的打印。 int 参数是缩进因子。

      JSONArray arr = ...
      System.out.println(arr.toString(4));
      

      它也适用于JSONObject

      您更大的问题是您的JSONArray 构造不正确。您应该向其中添加其他 JSONArrays 和 JSONObjects,但您正在添加其他对象。它们隐含地变成了Strings。在将它们放入数组之前,您需要将它们转换为 JSON。

      【讨论】:

      • 抱歉,问题不在这里...... JSONArray.toString(int) == JSONArray.toString() 具有默认值(prolly 根本没有格式化)
      • @Selvin 看起来他有两个问题!无论如何,我现在已经涵盖了两者。
      • 我很确定只有一个问题......格式问题不存在(他不需要格式化的 json - 格式化的 json 对问题的可读性更好)
      【解决方案4】:

      这对我来说非常适合

      String result = json.toString(4);
      

      我试图将它写入文件,这很完美。

      【讨论】:

        【解决方案5】:

        您可以使用 gson 库:https://code.google.com/p/google-gson/

        Gson gson = new Gson();
        String output = gson.toJson(object);
        

        【讨论】:

          【解决方案6】:

          试试这个:

          JsonArray jArray = //Your Json Array;
          JSONObject jObj = new JSONObject();
          jObj.put("test", jArray);
          String requiredString = jObj.optString("test");
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-08-27
            • 2019-12-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-01
            相关资源
            最近更新 更多