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>>(){});
Related
Im trying to get a key:value pair from a simple jsonString to add it after into a memory tab. If facing an issue cause my input is a string. and it looks like my loop isnot able to read the key value pair.
I read many topics about it, and im still in trouble with it. As you can see below
{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}
and my method, find only on object... the result is the same in my loop
public static ArrayHandler jsonSimpleObjectToTab(String data) throws ParseException {
if( data instanceof String) {
final var jsonParser = new JSONParser();
final var object = jsonParser.parse(data);
final var array = new JSONArray();
array.put(object);
final var handler = new ArrayHandler("BW_funct_Struct");
for( KeyValuePair element : array) {
handler.addCell(element);
Log.warn(handler);
}
return handler;
} else {
throw new IllegalArgumentException("jsonSimpleObjectToTab: do not support complex object" + data + "to Tab");
}
}
i also tryed before to type my array as a List, Object etc, without the keyValuePair object, i would appreciate some help.
Thanks again dear StackOverFlowers ;)
You can try this :
const json = '{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}';
map = new Map();
const obj = JSON.parse(json,(key,value) => {
map.set(key,value)
});
and you'll have every pair stored in map
Simply split the whole line at the commas and then split the resulting parts at the colon. This should give you the individual parts for your names and values.
Try:
supposing
String input = "\"nom\":\"BRUN\",\"prenom\":\"Albert\"";
then
String[] nameValuePairs = input.split(",");
for(String pair : nameValuePairs)
{
String[] nameValue = pair.split(":");
String name = nameValue[0]; // use it as you need it ...
String value = nameValue[1]; // use it as you need it ...
}
You can use TypeReference to convert to Map<String,String> so that you have key value pair.
String json = "{\"nom\":\"BRUN\",\"prenom\":\"Albert\",\"date_naiss\":\"10-10-1960\",\"adr_email\":\"abrun#gmail.com\",\"titre\":\"Mr\",\"sexe\":\"F\"}";
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<Map<String,String>> typeReference = new TypeReference<Map<String, String>>() {
};
Map<String,String> map = objectMapper.readValue(json, typeReference);
I just answered a very similar question. The gist of it is that you need to parse your Json String into some Object. In your case you can parse it to Map. Here is the link to the question with my answer. But here is a short version: you can use any Json library but the recommended ones would be Jackson Json (also known as faster XML) or Gson(by Google) Here is their user guide site. To parse your Json text to a class instance you can use ObjectMapper class which is part of Jackson-Json library. For example
public <T> T readValue(String content,
TypeReference valueTypeRef)
throws IOException,
JsonParseException,
JsonMappingException
See Javadoc. But also I may suggest a very simple JsonUtils class which is a thin wrapper over ObjectMapper class. Your code could be as simple as this:
Map<String, Object> map;
try {
map = JsonUtils.readObjectFromJsonString(input , Map.class);
} catch(IOException ioe) {
....
}
Here is a Javadoc for JsonUtils class. This class is a part of MgntUtils open source library written and maintained by me. You can get it as Maven artifacts or from the Github
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);
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 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)