How to parse json array using ajax?

Servlet. I am writing 2 JSON objects Stringin a 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 get this array:

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

He is showing [{"image":"myImageString"},{"html":"myHtmlString"}].

How to get these lines separately? The following does not work:

var image=result.image;
var html=result.html;
+4
source share
2 answers

The result in this case is an array of objects. Therefore, you should use them as an array:

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

It would be better if just returning one object:

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

                    out.write(obj1.toString());

In this case, your suggested code

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

will work.

+2
source

if you send an array, you must retrieve the objects from the array by index, e.g.

var image=result[0].image;

But if you want to get objects by name, for example

var image=result.image;

JsonObject a JsonArray

+1

Source: https://habr.com/ru/post/1621856/


All Articles