Steven Filipowicz
Steven Filipowicz

Reputation: 389

JSON to Java Object

I'm a little stuck with the following problem.

From a MongoDB I get this JSON string, and I want to get all the valuas of 'photo' and put them in an ArrayList. I've found some examples but they aren't working for me. I'm using GSON but a JSON solution will also be fine.

Return from MongoDB:

  [ { "url" : "/photos/avatar-1.jpg" , "photo" : "avatar-1.jpg" , "description" : "test     1"} , { "url" : "/photos/avatar-2.jpg" , "photo" : "avatar-2.jpg" , "description" : "test 2"} , { "url" : "/photos/avatar-3.jpg" , "photo" : "avatar-3.jpg" , "description" : "test 3"} , { "url" : "/photos/avatar-4.jpg" , "photo" : "avatar-4.jpg" , "description" : "test 4"}]

Putting into an ArrayList isn't the problem, but getting the 'photo' value. If someone could give me an example on how to loop through the 4 arrays and a System.out.println of the 'photo' value, that would be great!!

Thanks!

Upvotes: 1

Views: 493

Answers (3)

davidmontoyago
davidmontoyago

Reputation: 1833

Another option without creating DTOs, using Gson class StringMap:

String json = "[ { \"url\" : \"/photos/avatar-1.jpg\" , \"photo\" : \"avatar-1.jpg\" , \"description\" : \"test     1\"} , { \"url\" : \"/photos/avatar-2.jpg\" , \"photo\" : \"avatar-2.jpg\" , \"description\" : \"test 2\"} , { \"url\" : \"/photos/avatar-3.jpg\" , \"photo\" : \"avatar-3.jpg\" , \"description\" : \"test 3\"} , { \"url\" : \"/photos/avatar-4.jpg\" , \"photo\" : \"avatar-4.jpg\" , \"description\" : \"test 4\"}]";   

Gson gson = new Gson();     
Type type = new TypeToken<List<StringMap<String>>>(){}.getType();
List<StringMap<String>> stringMaps = gson.fromJson(json, type);
for (StringMap<String> map:stringMaps) {
    System.out.println(map.get("photo"));
}

EDIT

Imports:

import com.google.gson.Gson;
import com.google.gson.internal.StringMap;
import com.google.gson.reflect.TypeToken;

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

jsonString =[...];
Gson gson = new Gson();
PhotoDTO[] photos = gson.fromJson(jsonString, PhotoDTO[].class);

for(PhotoDTO photo : photos){
   System.out.println("photo -> " + photo.getPhoto());
}

PhotoDTO Class Definition

class PhotoDTO
{
  String url;
  String photo;
  String description;
  // setters & getters methods
}

Upvotes: 2

aroth
aroth

Reputation: 54846

Using the excellent json-simple library, you should be able to do something like this:

String json = "[{\"photo\": \"1.png\"}, {\"photo\": \"2.png\"}, " +
                "{\"photo\": \"3.png\"}, {\"photo\": \"4.png\"}]";
JSONArray photos = (JSONArray)JSONValue.parse(json);
for (int index = 0; index < photos.size(); index++) {
    JSONObject photoObj = (JSONObject)photos.get(index);
    System.out.println(photoObj.get("photo"));
}

Obviously replace the literal JSON text with the data that you're fetching from your database.

Upvotes: 2

Related Questions