4

Servlet side. I write 2 JSON String objects to JSON array:

Gson data = new Gson();
JsonArray arr = new JsonArray();

JsonObject obj1 = new JsonObject();
JsonElement element = data.toJsonTree(imgstr);
obj1.add("image", element);
arr.add(obj1);

JsonObject obj2 = new JsonObject();
JsonElement element1 = data.toJsonTree(strBuf);
obj2.add("html", element1);
arr.add(obj2);

out.write(arr.toString());

Ajax. I receive that array:

done(function(result) {
    console.log(result);
})

It shows [{"image":"myImageString"},{"html":"myHtmlString"}].

How to get that Strings separately? Following doesn't work:

var image=result.image;
var html=result.html;
0

2 Answers 2

2

Your result in this case in an array of objects. So you should acces them as an array:

var image=result[0].image;
var html=result[1].html;

It would be better though to just return one object:

                    JsonObject obj1 = new JsonObject();
                    JsonElement element = data.toJsonTree(imgstr);
                    obj1.add("image", element);
                    obj1.add("html", element1

                    out.write(obj1.toString());

In which case your suggested code

var image=result.image;
var html=result.html;

will work.

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

Comments

1

if you sending an array, you must retrieve objects from array by index like

var image=result[0].image;

But if you want to get objects by name like

var image=result.image;

you must send JsonObject not a JsonArray

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.