I have a requirement wherein I need to iterate over a List of Maps i.e. List<Map<String, Object>> grab the data from the list, and map it to a JSON file. Now the challenge is that I need to loop the data dynamically in the JSON file. Well, I do know how to map a single set of data to a JSON file using Thymeleaf but I'm not sure how to dynamically loop a JSON file using Thymeleaf.
The following thing is what I'm aware of -
I have a java class with a method that has the following code that will map the data from a HashMap to the JSON file.
public JSONObject response(){
Map<String, Object> map = new HashMap<>();
Context context = new Context();
String responsePayload = null;
JSONObject jsonObject = null;
data.put("name", "Wayne Rooney")
data.put("profession", "Footballer")
context.setVariable("data", data);
responsePayload = templateEngine.process("resource/payload", context);
jsonObject = new JSONObject(responsePayload);
}
This is how the payload.json file looks
{
"name": "[(${data['name']})]",
"profession": "[(${data['profession']})]"
}
So, my code works smoothly when only a single instance of HashMap data is mapped to the JSON file, but my next requirement is how do I loop a List of Maps i.e. List<Map<String, Object>> and map the data in my json file?
For e.g. Consider now I've a List<Map<String, Object>> instead of Map<String, Object>
public JSONObject response(){
List<Map<String, Object>> listOfMap = new ArrayList<>();
Map<String, Object> data1 = new HashMap<>();
Map<String, Object> data2 = new HashMap<>();
Map<String, Object> data3 = new HashMap<>();
Context context = new Context();
String responsePayload = null;
JSONObject jsonObject = null;
data1.put("name", "Wayne Rooney")
data1.put("profession", "Footballer")
data2.put("name", "Cristiano Ronaldo")
data2.put("profession", "Footballer")
data3.put("name", "Sir Alex Ferguson")
data3.put("profession", "Manager")
listOfMap.add(data1);
listOfMap.add(data2);
listOfMap.add(data3);
context.setVariable("data", listOfMap);
responsePayload = templateEngine.process("resource/payload", context);
jsonObject = new JSONObject(responsePayload);
return jsonObject;
}
So now how do I map this list of data to a JSON file? What changes do I need to make in the JSON file?
I appreciate it if someone helps here.
Thank you!
Related
I am using transaction for dynamodb. And transaction Put request takes com.amazonaws.services.dynamodbv2.document.Item as input param. So, I need to convert a POJO to a Map.
So far I have tried converting the object to string using Jackson and then converting the string to an item.
Below is the code I have tried.
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Item item = new Item().withJSON("document", jsonStr);
Map<String,AttributeValue> attributes = ItemUtils.toAttributeValues(item);
return attributes.get("document").getM();
Problem is, a field of 'Set' type returns 'List' after conversion.
Any suggestion how to overcome this?
Below code should solve your convertion:
Map<String, AttributeValue> valueMap = ItemUtils.toAttributeValues(item);
CustomEntity entity = dynamoDBMapper.marshallIntoObject(CustomEntity.class, valueMap);
I'm currently having the following issue:
I wish to loop through a set of JSON files. I want to filter out certain JSON files that match a filter. This filter is another JSON object.
MongoDB is able to do this; you give a JSON object as parameter and it will list documents containing the given JSON elements.
I need a flatfile version of this, but I am not able to succeed. I'm using GSON as my JSON library.
Consumes an array of file paths that each contain a JSON string, and a JsonObject that represents the filter rules. Returns a list of file paths that match the filter rules.
public List<String> filter(String[] filePaths, JsonObject rules) throws FileNotFoundException {
final List<String> filtered = new ArrayList<String>();
final Set<Map.Entry<String, JsonElement>> rulesEntries = rules.entrySet();
for (String path : filePaths) {
final Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path))));
final JsonObject file = jsonParser.parse(reader).getAsJsonObject();
final Set<Map.Entry<String, JsonElement>> fileEntries = file.entrySet();
if (fileEntries.containsAll(rulesEntries)) filtered.add(path);
}
return filtered;
}
In java I am trying to convert a Map to json string. using code below
private void sendResponse(Map<String, String> responseMap) throws IOException
{
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
JSONObject json = new JSONObject(responseMap);
ps.println(json.toString());
}
The variable
json results in {"empty":false} the map contains valid keyvalue pairs.
The map contains values like this
responseMap.put("response", "ok");
responseMap.put("versionname", "dummy");
responseMap.put("versioncode", "dummy");
responseMap.put("package","dummy");
responseMap.put("deviceid", "unknown");
responseMap.put("devicename", "dummy");
responseMap.put("synclocation", null);
responseMap.put("extra", "");
The code I am using comes from https://github.com/douglascrockford/JSON-java
any ideas why its not working
?
Map to Json, Json to Map? I use Gson lib. There is no problem.
Map to Json String
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Map<String, String> map = new HashMap<String, String>();
map.put("111", "AAAAA");
map.put("222", "BBBBB");
String mapString = gson.toJson(map);
System.out.println(mapString);
Output
{
"222": "BBBBB",
"111": "AAAAA"
}
Json String to Map
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String mapString = "{\"222\": \"BBBBB\",\"111\": \"AAAAA\"}";
Map<String, String> map = gson.fromJson(mapString, Map.class);
System.out.println(map.get("111"));
Output
AAAAA
I'm Workin with Mongo using Jongo, when I do a query I receive a LinkedHashMap as result.
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
LinkedHashMap data = new LinkedHashMap();
data = (LinkedHashMap) one.next();
String content = data.toString();
}
the problem is that if the json is {"user":"something"} content will be {user=something}, it is not a json is only toString method from HashMap.
How I can get the original JSON?
I don't have a class to map the response and it isn't a solution create a map class, that is why I use a Object.class.
If you have access to some JSON library, it seems like that's the way to go.
If using org.json library, use public JSONObject(java.util.Map map):
String jsonString = new JSONObject(data).toString()
If Gson, use the gson.toJson() method mentioned by #hellboy:
String jsonString = new Gson().toJson(data, Map.class);
You can use Gson library from Google to convert any object to JSON. Here is an example to convert LinkedHashMap to json -
Gson gson = new Gson();
String json = gson.toJson(map,LinkedHashMap.class);
One of the com.mongodb.BasicDBObject constructors takes a Map as input. Then you just have to call the toString() on the BasicDBObject object.
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
LinkedHashMap data= new LinkedHashMap();
data= (LinkedHashMap) one.next();
com.mongodb.BasicDBObject bdo = new com.mongodb.BasicDBObject(data);
String json = bdo.toString();
}
I resolved the problem using the following code:
Iterator one = (Iterator) friends.find(query).projection("{_id:0}").as(Object.class);
while (one.hasNext()) {
Map data= new HashMap();
data= (HashMap) one.next();
JSONObject d = new JSONObject();
d.putAll(data);
String content=d.toString();
}
if(data instanceof LinkedHashMap){
json=new Gson.toJson(data,Map.class).toString();
}
else{
json=data.toString();
}
return Document.parse(json);
I try to make this json format:
[{"x":1392440400000,"title":"!"},{"x":1392465600000,"title":"!"}]
I tried it out with the jsonGenerator
This is my code:
JsonFactory f = new JsonFactory();
StringWriter sw = new StringWriter();
JsonGenerator g = f.createJsonGenerator(sw);
while {
g.writeStartObject();
g.writeNumberField("x",111111);
g.writeStringField("title","!");
g.writeEndObject();
}
g.close();
return "["+sw.toString()+"]";
But my output is like that ist like that:
[{"x":1392440400000,"title":"!"} {"x":1392465600000,"title":"!"}]
Can anybody help me to make the correct Json output with a comma between the objects ?
You can use the ObjectMapper to generate the output.
So this could be something like this.
ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("x", 1392440400000l);
data.put("title", "!");
HashMap<String, Object> data2 = new HashMap<String, Object>();
data2.put("x", 1392440400000l);
data2.put("title", "!");
List out = new ArrayList();
out.add(data);
out.add(data2);
String val = mapper.writeValueAsString(out);
I'm not using jackson, but for this specific scenario, you need your g.writeStartObject(); and g.writeEndObject(); inside the loop. (Because you're essentially trying to create an Array of Objects, right?)