JSONArray 到 Java 中的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26776200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:35:05  来源:igfitidea点击:

JSONArray to String in java

javaandroidarraysjsonstring

提问by Rikkert09

I have an JSONArraythat looks like this:

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

enter image description here

在此处输入图片说明

how can i convert that to a string?

我如何将其转换为字符串?

if i try:

如果我尝试:

json.toString();

the string is:

字符串是:

["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"]

but i want something like this:

但我想要这样的东西:

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

EDIT:

编辑:

this a snipped how i make the json array:

这是我如何制作 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();

回答by Nemanja Maksimovic

The problem is not the JSONArray.toString(), as @Selvin mentioned.

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

From JSONArray source:

来自 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();
}

The problem is that you need to convert your ChecklistAnswer to JSON object first for your JSONArray to work properly.

问题是您需要先将 ChecklistAnswer 转换为 JSON 对象,以便 JSONArray 正常工作。

Again from Javadoc:

再次来自 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.

...

...

回答by Rikkert09

In my ChecklistAnwer class i added:

在我的 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;
}

and in my other class:

在我的另一堂课中:

JSONArray answers = new JSONArray();

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

answers.put(answer.toJsonObject());

if i filled the array:

如果我填充了数组:

String js = answers.toString(1);

and that returns:

然后返回:

[
 {
  "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
 }
]

thanks to @Selvin

感谢@Selvin

回答by Nouman Ch

This works perfectly for me

这对我来说非常有效

String result = json.toString(4);

I was trying to write it into the file and this is perfect.

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

回答by chiastic-security

You don't need to use any extra libraries. The JSONArrayclass has an extra .toString(int)methodthat does the pretty printing for you. The intparameter is the indentation factor.

您不需要使用任何额外的库。该JSONArray班有一个额外的.toString(int)方法,做漂亮的印花为您服务。该int参数是缺口因素。

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

It also works with a JSONObject.

它也适用于JSONObject.

Your bigger problem is that your JSONArrayis not being constructed properly. You're supposed to add other JSONArrays and JSONObjects to it, but you're adding other objects. They are implicitly being turned into Strings. You need to convert them to JSON before putting them into your array.

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

回答by Eldhose M Babu

Try this :

试试这个 :

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

回答by Piotr Golinski

You can use gson library : https://code.google.com/p/google-gson/

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

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