2

I have an JSONArray that looks like this:

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:

   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();
10
  • 1
    it works as intended ... you just put ChecklistAnswer object into array ... not JSONObject ... ChecklistAnswer.toString() returns "xx.xx.xx.ChecklistAnswer@XXX" ... so either override ChecklistAnswer.toString method to return json string or make a function to translate ChecklistAnswer to JSOObject Commented Nov 6, 2014 at 9:51
  • show codes used for json parsing Commented Nov 6, 2014 at 9:54
  • i added some code @CapDroid Commented Nov 6, 2014 at 9:58
  • @Rikkert09 did you got answer ? Commented Nov 6, 2014 at 10:02
  • 2
    instead answers.add(answer); use answers.add(answer.toJSONObject()); (and yeah, you have to write toJSONObject method inside ChecklistAnswer by yourself - which should be pretty simple - like putting all ChecklistAnswer`s properties into new JSONObject) Commented Nov 6, 2014 at 10:13

6 Answers 6

2

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.

...

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

3 Comments

sorry but problem is not here ... JSONArray.toString(int) == JSONArray.toString() with default values (prolly without formating at all)
@Selvin Looks like he had two problems! In any case, I've now covered both.
i'm pretty sure that there is only one problem ... the formatting problem doesn't exists (he doesn't need formatted json - the formatted json is better for question's readability)
0

This works perfectly for me

String result = json.toString(4);

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

Comments

-1

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

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

Comments

-1

Try this :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.