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?)
Related
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!
Consider the following code:
public void testDumpWriter() {
Map<String, Object> data = new HashMap<String, Object>();
data.put("NAME1", "Raj");
data.put("NAME2", "Kumar");
Yaml yaml = new Yaml();
FileWriter writer = new FileWriter("/path/to/file.yaml");
for (Map.Entry m : data.entrySet()) {
String temp = new StringBuilder().append(m.getKey()).append(": ").append(m.getValue()).toString();
yaml.dump(temp, file);
}
}
The output of the above code is
'NAME1: Raj'
'NAME2: Kumar'
But i want the output without the single quotes like
NAME1: Raj
NAME2: Kumar
This thing is very comfortable for parsing the file.
If anyone have solution, please help me to fix. Thanks in advance
Well SnakeYaml does exactly what you tell it to: For each entry in the Map, it dumps the concatenation of the key, the String ": ", and the value as YAML document. A String maps to a Scalar in YAML, and since the scalar contains a : followed by space, it must be quoted (else it would be a key-value pair).
What you actually want to do is to dump the Map as YAML mapping. You can do it like this:
public void testDumpWriter() {
Map<String, Object> data = new HashMap<String, Object>();
data.put("NAME1", "Raj");
data.put("NAME2", "Kumar");
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
FileWriter writer = new FileWriter("/path/to/file.yaml");
yaml.dump(data, writer);
}
The documentation in Jackson is horrible and it only states how it is possible to create JSON from objects and streams, not piece by piece. I cannot find the term to be able to search for more examples/documentation.
I would like to do something like the following.
JsonObject jsonObject = new JsonObject().add("type", "unregister").add("id",id);
return jsonObject.toString();
Which would return {"type":"unregister","id":2} as an example. Can anyone nudge me in the right direction?
The corresponding JsonObject in Jackson is ObjectNode. You can use its various xyzNode(...) factory methods to produce JsonNode subtype instances. You can then use ObjectNode#set(String, JsonNode) to add them.
JsonNodeFactory nc = new JsonNodeFactory(false); // or true, depending
ObjectNode root = new ObjectNode(nc);
TextNode text = root.textNode("unregister");
NumericNode id = root.numberNode(2);
root.set("type", text);
root.set("id", id);
Then
System.out.println(node);
produces
{"type":"unregister","id":2}
You can also create an ObjectNode through the ObjectMapper which uses the ObjectMapper's JsonNodeFactory.
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = mapper.createObjectNode();
Jackson maps Java Objects to JSON, so their documentation is telling you what it does (it does not provide a sort of builder API to arbitrarily compose JSON documents)
If you want to map arbitrary key/values, use a Map<String, Object> and use Jackson to turn it into JSON. You can mix heterogeneous map values and get the result you want this way, pseudo:
Map<String, Object> map = new HashMap<>();
map.put("type", "unregister");
map.put("id", id);
StringWriter sw = new StringWriter();
mapper.writeValue(sw, map); // mapper is a ObjectMapper instance
System.out.println(sw.toString());
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 want to use jackson to convert a ArrayList to a JsonArray.
Event.java : this is the java bean class with two fields "field1", "field2" mapped as JsonProperty.
My goal is:
Convert
ArrayList<Event> list = new ArrayList<Event>();
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
To
[
{"field1":"a1", "field":"a2"},
{"field1":"b1", "field":"b2"}
]
The way I can think of is:
writeListToJsonArray():
public void writeListToJsonArray() throws IOException {
ArrayList<Event> list = new ArrayList<Event>();
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
OutputStream out = new ByteArrayOutputStream();
JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createJsonGenerator(out, JsonEncoding.UTF8);
ObjectMapper mapper = new ObjectMapper();
jGenerator.writeStartArray(); // [
for (Event event : list) {
String e = mapper.writeValueAsString(event);
jGenerator.writeRaw(usage);
// here, big hassles to write a comma to separate json objects, when the last object in the list is reached, no comma
}
jGenerator.writeEndArray(); // ]
jGenerator.close();
System.out.println(out.toString());
}
I am looking for something like:
generator.write(out, list)
this directly convert the list to json array format and then write it to outputstream "out".
even greedier:
generator.write(out, list1)
generator.write(out, list2)
this will just convert/add in the list1, list2 into a single json array. then write it to "out"
This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:
public void writeListToJsonArray() throws IOException {
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, list);
final byte[] data = out.toByteArray();
System.out.println(new String(data));
}
I can't find toByteArray() as #atrioom said, so I use StringWriter, please try:
public void writeListToJsonArray() throws IOException {
//your list
final List<Event> list = new ArrayList<Event>(2);
list.add(new Event("a1","a2"));
list.add(new Event("b1","b2"));
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, list);
System.out.println(sw.toString());//use toString() to convert to JSON
sw.close();
}
Or just use ObjectMapper#writeValueAsString:
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(list));
In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.
List<Apartment> aptList = new ArrayList<Apartment>();
Apartment aptmt = null;
for(int i=0;i<5;i++){
aptmt= new Apartment();
aptmt.setAptName("Apartment Name : ArrowHead Ranch");
aptmt.setAptNum("3153"+i);
aptmt.setPhase((i+1));
aptmt.setFloorLevel(i+2);
aptList.add(aptmt);
}
mapper.writeValueAsString(aptList)