简体   繁体   中英

JSONArray to String in java

I have an JSONArray that looks like this:

在此处输入图片说明

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:

   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();

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

From JSONArray source:

/**
 * 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.

Again from 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.

...

In my ChecklistAnwer class i added:

   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

You don't need to use any extra libraries. The JSONArray class has an extra .toString(int) method that does the pretty printing for you. The int parameter is the indentation factor.

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

It also works with a JSONObject .

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

This works perfectly for me

String result = json.toString(4);

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

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

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

Try this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM