json map to string failure in java - java

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

Related

How to dynamically loop a JSON file using Thymeleaf in Spring boot

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!

Convert json String containing array to Map in Java

I need to convert String to Map for the following json string in Java:
Please note that this json string has array in it and that is where I am facing the issue:
{
"type":"auth",
"amount":"16846",
"level3":{
"amount":"0.00",
"zip":"37209",
"items":[
{
"description":"temp1",
"commodity_code":"1",
"product_code":"11"
},
{
"description":"temp2",
"commodity_code":"2",
"product_code":"22"
}
]
}
}
I tried couple of ways as mentioned in below links:
Convert JSON string to Map – Jackson
Parse the JSONObject and create HashMap
Error I am getting:
JSON parser error: Can not deserialize instance of java.lang.String
out of START_OBJECT token ... }; line: 3, column: 20] (through
reference chain:
java.util.LinkedHashMap["level3"])com.fasterxml.jackson.databind.JsonMappingException:
Can not deserialize instance of java.lang.String out of START_OBJECT
token
So to give more details about what I am doing with the Map is, this map will be converted back to the json string using following method:
public static String getJSON(Object map) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
OutputStream stream = new BufferedOutputStream(byteStream);
JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(stream, JsonEncoding.UTF8);
objectMapper.writeValue(jsonGenerator, map);
stream.flush();
jsonGenerator.close();
return new String(byteStream.toByteArray());
}
You cannot parse your JSON content into a Map<String, String>
(like it is done in the two links you posted).
But you can parse it into a Map<String, Object>.
For example like this:
ObjectMapper mapper = new ObjectMapper();
File file = new File("example.json");
Map<String, Object> map;
map = mapper.readValue(file, new TypeReference<Map<String, Object>>(){});

Java gson, ClassCastException on decoding to Map<String,String[]>

I want to decode a json string like {"username":["emmet"]} to a Map<String,String[]> object.
using following code:
String json = "{\"username\":[\"emmet\"]}";
Gson gson = new GsonBuilder().create();
Map<String,String[]> map = new HashMap<>();
map = (Map<String,String[]>)gson.fromJson(json, map.getClass());
String[] val = map.get("username");
System.out.println(val);
this exception occurs:
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.String;
at com.company.Main.main(Main.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Gson has decoded my object as a Map<String, ArrayList<String>> object instead of Map<String,String[]> object. How can I force gson to decode my object as Array not ArrayList?
I'm using gson-2.8.1.
Gson converts json array to a java List, so when you trying to get the usernames as String[] you getting an ClassCastException
If you want to get it as a String[] use it that way :
String json = "{\"username\":[\"emmet\"]}";
Gson gson = new GsonBuilder().create();
Map<String,List<String>> map = new HashMap<>();
map = (Map<String,List<String>>)gson.fromJson(json, map.getClass());
List<String> usernames = map.get("username");
String[] val = usernames.toArray(new String[0]);
System.out.println(val);
That will work for you
You can parse everything out and place it into a Map manually. Here is some code that demonstrates how you could do this
String jsonString = "{\"username\":[\"emmet\"]}";
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();
Set<String> keys = jsonObject.keySet();
Map<String, String[]> map = new HashMap<>();
for(String key:keys){
JsonElement jsonElement = jsonObject.get(key);
if(jsonElement.isJsonArray()){
JsonArray jsonArray = jsonElement.getAsJsonArray();
String[] strings = new String[jsonArray.size()];
for(int i = 0; i < jsonArray.size(); i++){
strings[i] = jsonArray.get(i).getAsString();
}
map.put(key, strings);
} else {
//Handle other instances such as JsonObject, JsonNull, and JsonPrimitive
}
}

Convert from LinkedHashMap to Json String

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);

How can i make a json file with java jsonGenerator?

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?)

Categories

Resources