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!
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
}
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.
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;
Related
Please I have List containing below value
[ { "sender" : "sys" , "message" : [ "Hello, " , "how are you?"] ,"transaction_date" : { "$date" : "2019-02-14T17:34:12.705Z"} , "has_suggestions" : true } , { "sender" : "user" , "message" : [ "Hello." , "hey you"] , "visited" : true , "transaction_status" : "Succeded" , "transaction_date" : { "$date" : "2019-02-14T17:34:12.705Z"} , "has_suggestions" : true , "suggestion_list" : [ "Yes, I am." , "No, I am not."] , "suggestion_list_type" : "buttons"}, { "sender" : "sys" , "message" : { "has_form" : true , "form_type" : "prehandover_form" , "data" : { "text" : [ "Kindly provide your info"]}} , "visited" : false , "transaction_status" : "Succeded" , "transaction_date" : { "$date" : "2019-02-14T17:34:15.386Z"}}]
I tried to traverse through the content of the JSON data using Jackson JsonNode below the the code:
ObjectMapper object = new ObjectMapper();
JsonNode jsonNode = object.readTree(value);
String sender = jsonNode.get("sender").textValue();
But am getting a Exception in thread "main" java.lang.NullPointerException
Please any help to traverse through the the JSON data will highly be appreciated.
You need to get the ArrayList from JsonNode.
Here is your solution.
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
String sender = jsonNode.get(0).get("sender").textValue();
JsonNode contains multiple objects. Due to read all sender elements, you may use following code.
public static void main(String[] args) throws IOException {
File file = new File("src\\main\\java\\json.txt");
FileInputStream value = new FileInputStream(file);
ObjectMapper object = new ObjectMapper();
JsonNode jsonNode = object.readTree(value);
for (int i=0;i<jsonNode.size();i++){
System.out.println(jsonNode.get(i).findValue("sender").textValue());
}
}
This is the values of my data stored in mongo db. How am I able to retrieve all the data of "HomeTown" and store it all into a list? My list would contain AA, AA, BB, BB, etc... I want to use that array list to create a for loop of each Hometown.
Sample mongo data
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "AA" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "AA" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "BB" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "BB" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
How can I get all of the values of "HomeTown" in Java into an array? I am trying to create a for loop with the HomeTown Names. I am currently using mongodb dependency through Spring boot. I am not sure how would I implement mongodb into my java to use mongo db.
Attempt/Problem
I was able to retrieve mongodb values in a list using the following code. I am trying to convert this list to a arraylist.
public List<AppPortModel> getAppPortList() {
List<ApServerModel> objLst = mongoOperations.findAll(ApServerModel.class);
String[] apServerArray = new String[objLst.size()];
for(int i = 0; i < objLst.size(); i++) {
apServerArray[i] = objLst.get(i);
}
Error on objLst.get(i)
Type mismatch: cannot convert from ApServerModel to String
Attempt #2 Following Sagar Example
#Autowired
MongoOperations mongoOperations;
MongoCollection<ApServerModel> myCollection = **mongoOperations.getCollection("apAllCustomer");**
List<ApServerModel> result = myCollection.find().into(new ArrayList<>());
Error on mongoOperations.getCollection
Type mismatch: cannot convert from DBCollection to MongoCollection<ApServerModel>
Looks like you're using mongo 3.x driver.You'll need to use something like this.
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("mkoydb");
MongoCollection<Document> myCollection = db.getCollection("apAllCustomer");
List<Document> result = myCollection.find().into(new ArrayList<>());
Fix for Attempt 1:
public List<AppPortModel> getAppPortList() {
List<ApServerModel> objLst = mongoOperations.findAll(ApServerModel.class);
String[] apServerArray = new String[objLst.size()];
for(int i = 0; i < objLst.size(); i++) {
apServerArray[i] = objLst.get(i).getHomeTown();
}
Fix for Attempt 2:
DBCollection dbCollection = mongoOperations.findAll(AppServreModel.class, "apAllCustomer");
You can call toArray() which, intuitively, returns a List<DBObject>.
List<DBObject> myList = null;
DBCursor myCursor=myCollection.find(new BasicDBObject(),"HomeTown");
myList = myCursor.toArray();
if you are using java driver with version 3.0 and above you can also do
collection.find().projection(Projections.include("HomeTown"));
You can use projection to retrieve only required fields.
db.apAllCustomer.find( ..., { HomeTown: 1 } );
In Java it depends on the API you use. See this for Spring Data:
SpringData MongoDB Using projection
MongoDB-Java:
Restrict fields in Result
I have a JSON file and I do not know how can I parse the part of "coordinates", others done already. It seems null, others seem ok when I try to reach them. I guess, coordinates part is another class defined in cities part. Could you please help me to get coordinates of cities?
I kept my cities in a linkedlist.
"cities" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
}
static List<City> allCities = new LinkedList<City>();
static List<Flight> allFlights = new LinkedList<Flight>();
static JSONArray cities;
static JSONArray flights;
FileReader reader = new FileReader("csair.json");
JSONObject CSAirData = (JSONObject) JSONValue.parse(reader);
cities = (JSONArray) CSAirData.get("cities");
flights = (JSONArray) CSAirData.get("routes");
Assuming "cities" is an attribute of variable myVar, like this
var myVar = {
"cities": [
{
"code": "SCL",
"name": "Santiago",
...
}
]
};
then you could access "coordinates" by doing
myVar.cities[0].coordinates
"cities" corresponds to an array
the first element in the array (index = 0) is an object
that object has an attribute called "coordinates", which references another object
Edit
Now that I see you are using Java code, you just need to transform this syntax into Java.
We know that "cities" is a JSONArray.
JSONObject city = cities.get(0); // Get the first city in the array (index = 0)
JSONObject coordinates = city.getJSONObject("coordinates");
int coordinates_s = coordinates.getInt("S");
int coordinates_w = coordinates.getInt("W");
I have a different use case where fields in POJO itself stores JSON data, basically grouping of all data.
Now i want the complete JSON generated from above POJO.
At present i am using this method
private static Gson gson = new Gson();
public static String convertObjectToJSON(Object object) throws Exception {
String jsonResponse = gson.toJson(object);
return jsonResponse;
}
But getting output with escape characters around double quotes like below
{ \"_id\" : 234242, \"name\" : \"carlos\"}
I tried various options in GsonBuilder, but not working.
Basically, i am just grouping multiple JSON data and sending it across.
Could you please do the needful help to get rid of the escape characters around double quotes.
UPDATE:
Question is : I have 3 JSONs and need to combine them into a single JSON and need to pass it to html5 client through Spring MVC. As of now i am added the 3 JSONs into a POJO and trying to convert the same to JSON. Same is explained above.
Thanks & Regards
Venkat
I have tried below sample code and it doesn't have any escape characters around double quotes.
class MyPOJO{
private int _id;
private String name;
// getter & setter
}
String json="{ \"_id\" : 234242, \"name\" : \"carlos\"}";
MyPOJOobj=new Gson().fromJson(json, MyPOJO.class);
System.out.println(new Gson().toJson(obj));
output:
{"_id":234242,"name":"carlos"}
EDIT
If you want to combine 3 JSON string then It will be stored as List of object as illustrated below:
sample code:
String json = "[" +
" { \"_id\" : 1, \"name\" : \"A\"}," +
" { \"_id\" : 2, \"name\" : \"B\"}," +
" { \"_id\" : 3, \"name\" : \"C\"}" +
"]";
Type type = new TypeToken<ArrayList<MyPOJO>>() {}.getType();
ArrayList<MyPOJO> obj = new Gson().fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
output:
[
{
"_id": 1,
"name": "A"
},
{
"_id": 2,
"name": "B"
},
{
"_id": 3,
"name": "C"
}
]
I'm getting an Json and then using Gson to deserialize it in an object where value is a String not an object.. so i'm trying to put that object into a String variable - not deserialized
I want to do something like this:
"{value" : {"id":"2"}} -> {"value" : "{\"id\":\"2\"}"}
I replaced the "value" : { with "value" : "{ like this:
result = result.replace("\"value\" : {", "\"value\" : \"{");
and then I replaced the }} like this:
result = result.replace("}}", "}\"}");
And my result was (after replacing everything):
{"value" : "{"id":"2","name":"game2"}"}
the only problem now: i also want to replace the " with \" but only inside the "{ ... }" I can't figure that out.
EDIT:
Incoming Json:
{"path" : "/gdi/games/2", "key" : "detail", "value" : {"id":"2","name":"game2"}},
{"path" : "/gdi/games/4", "key" : "detail", "value" : {"id":"4","name":"game4"}},
{"path" : "/gdi/games/6", "key" : "detail", "value" : {"id":"6","name":"game6"}}
The problem: value: could be anything (text) so I only want to store everything which cames between { } in my Object which become deserialized in an object that looks like:
String path;
String key;
String value;
To achieve this I have to escape the object (which is in "value") like it is String - After escaping that Gson can deserialize it for me.
Json needed:
{"path" : "/gdi/games/2", "key" : "detail", "value" : "{\"id\":\"2\",\"\name\":\"game2\"}"},
{"path" : "/gdi/games/4", "key" : "detail", "value" : "{\"id\":\"4\",\"\name\":\"game4\"}"},
{"path" : "/gdi/games/6", "key" : "detail", "value" : "{\"id\":\"6\",\"\name\":\"game6\"}"}
This does the trick:
input = input.replaceAll("(?=\"[^{}]*\\})", "\\\\");
It uses a look ahead to assert that the next curly bracket found after a double quote is a right curly - meaning the double quote must be within a pair of curly brackets.
The replacement term is a literal backslash - four backslashes needed due to double-escape: one for java string literal, one for regex escape.
Here's some test code using your sample input an producing your expected output:
String input =
"{\"path\" : \"/gdi/games/2\", \"key\" : \"detail\", \"value\" : {\"id\":\"2\",\"name\":\"game2\"}}," +
"{\"path\" : \"/gdi/games/4\", \"key\" : \"detail\", \"value\" : {\"id\":\"4\",\"name\":\"game4\"}}," +
"{\"path\" : \"/gdi/games/6\", \"key\" : \"detail\", \"value\" : {\"id\":\"6\",\"name\":\"game6\"}}";
input = input.replaceAll("(?=\"[^{}]*\\})", "\\\\");
System.out.println(input);
Output:
{"path" : "/gdi/games/2", "key" : "detail", "value" : {\"id\":\"2\",\"name\":\"game2\"}},
{"path" : "/gdi/games/4", "key" : "detail", "value" : {\"id\":\"4\",\"name\":\"game4\"}},
{"path" : "/gdi/games/6", "key" : "detail", "value" : {\"id\":\"6\",\"name\":\"game6\"}}
You can use Jackson library to map data to a class.
http://www.journaldev.com/2324/jackson-json-processing-api-in-java-example-tutorial
For printing backslashes - example
public static void main(String[] args) {
String a="{\"id\":\"2\",\"name\":\"game2\"}";
System.out.println("Before - "+a);
System.out.println("After - "+a.replace("\"", "\\\""));
}
output -
Before - {"id":"2","name":"game2"}
After - {\"id\":\"2\",\"name\":\"game2\"}
you just need to add double \ if you want to add "\"
for example: System.out.println("\\"");
print this statement you will get : \"
String abc: "\\"";