Json string to Hashmap Java [duplicate] - java

This question already has answers here:
Jackson - Deserialize using generic class
(10 answers)
Closed 7 months ago.
I was trying to convert the json string to hashmap using com.fasterxml.jackson.databind.ObjectMapper.
String str = "{\"key\":\"[{\"one\":\"value\"}]\"}";
ObjectMapper mapper = new ObjectMapper();
try {
HashMap<String, String> map = mapper.readValue(str, HashMap.class);
System.out.println(map);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
But getting the below error,
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('o' (code 111)): was expecting comma to separate Object entries
at [Source: (String)"{"key": "[{"one":"value"}]"}"; line: 1, column: 14]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:2391)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:735)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:659)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipComma(ReaderBasedJsonParser.java:2382)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextFieldName(ReaderBasedJsonParser.java:947)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringKeyMap(MapDeserializer.java:594)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:437)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:32)
at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:323)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4674)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3629)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3597)
at com.sample.quick.check.one.App.main(App.java:15)
In the json string, I want the key and value as string and store them into hashMap. I don't want to parse the value in to jsonArray.

JSON string is not valid. If the value of key is a string, then you need to escape \". This means you need to tell to 'Java' to escape also the \ character.
Change the string to String str = "{\"key\":\"[{\\\"one\\\":\\\"value\\\"}]\"}";
This means:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
class Scratch {
public static void main(String[] args) {
String str = "{\"key\":\"[{\\\"one\\\":\\\"value\\\"}]\"}";
ObjectMapper mapper = new ObjectMapper();
try {
HashMap<String, String> map = mapper.readValue(str, HashMap.class);
System.out.println(map);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Converting Map to JSON in Java

I am having a map
Map<String, Application.RiskFactor> appRiskFactorsMap = app.getRiskFactors();
It has this data kind of in it
{risk1=Application.RiskFactor(risk=risk1, question=question1,
factor=true), risk2=Application.RiskFactor(risk=risk2,
question=question2?, factor=true),
risk3=Application.RiskFactor(risk=risk3, question=question3?,
factor=true)}
I am converting it into JSON and having this output.
{"risk1":{"risk":"risk1","question":"question1?","factor":"true"},"":
{"risk":"risk2","question":"question2?","factor":"true"},"risk3":
{"risk":"risk3","question":"question3?","factor":"true"}}
I have this JSON converter class
package system.referee.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public final class JsonUtils {
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
// Ignore unknown fields while deserialization
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// Ignore null & Optional.EMPTY fields while serialization
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
}
public static <T> String toJson(T obj) {
try {
return MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
return "";
}
}
public static <T> T fromJson(String json, Class<T> type) {
try {
return MAPPER.readValue(json, type);
} catch (JsonProcessingException e) {
return null;
}
}
}
I want to print the JSON in this format
{"risk":"risk1","question":"question1?","factor":"true"},
{"risk":"risk2","question":"question2?","factor":"true"},
{"risk":"risk3","question":"question3?","factor":"true"}
is there any way to achieve that? I am unable to find any help with this. thanks a lot
You should ignore keys and serialise only values:
JsonUtils.toJson(appRiskFactorsMap.values())
Result will be a JSON Array.

A space in JSON value causes "unexpected token END OF FILE at position 11" exception when parsing in Java

When I use the parser from org.json.simple.parser.* I get an exception whenever one of the values in JSON contains a space. For example:
{"name":"Adam"}
would parse correctly, but
{"name":"Ad am"}
would cause "unexpected token END OF FILE at position 11" exception
Here is the code that I use to convert a JSON string into a JSONObject.
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringJSON);
Try to get through this below example and each value contains space except integer one and giving this example just because of you don't have shared your source code.
JSON File(personal_detail.json):
{
"name":"arif mustafa",
"age":26,
"address":["district is Korba","state is Chhattisgarh","country is India"]
}
Java source to read the JSON file format:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JSONExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("src/resources/personal_detail.json"));
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject + "\n");
String name = (String) jsonObject.get("name");
System.out.println("name : " + name);
long age = (Long) jsonObject.get("age");
System.out.println("age : " + age);
//get Object loop array
JSONArray address = (JSONArray) jsonObject.get("address");
System.out.println("address is : ");
Iterator<String> iterator = address.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}

java - getting child class object in parent abstract class function

I am trying to write an abstract class which will map the string values to the object member-variables and vice versa using ObjectMapper of jackson-databind. This abstract class will be extended by each pojo of json.
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class JsonToString {
public JsonToString toObject(String jsonString){
ObjectMapper mapper = new ObjectMapper();
try {
mapper.readValue(jsonString, this.getClass());//problem
System.out.println("inside object function of jsontostring : "+this);
} catch (JsonParseException e) {
System.out.println("Exception occured in mapping jsonString received to object" + e);
} catch (JsonMappingException e) {
System.out.println("Exception occured in mapping jsonString received to object" + e);
} catch (IOException e) {
System.out.println("Exception occured in mapping jsonString received to object" + e);
}
return this;
}
public String toString(){
ObjectMapper mapper = new ObjectMapper();
String json = new String();
try {
json = mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
System.out.println("Trouble in mapping object to string in json class : "+this.getClass().getName());
}
return json;
}
}
this class will be extended by each json pojo.
So here I want to return the object of child class for which the mappings has been done. Can someone please help me get the object and return it.
I am calling this method in this manner :
ITAGResponseInfo response = new ITAGResponseInfo();
response = (ITAGResponseInfo)response.toObject(cOutput);
System.out.println("Printing from the itagresponseinfo object : "+response);
Here ITAGResponseInfo extends the JsonToString class.

java.lang.String cannot be cast to org.json.simple.JSONObject simple-json

I am getting strange problem while trying to parse a simple json using simple-json by google.
Here is my code which is not working:
String s = args[0].toString();
JSONObject json = (JSONObject)new JSONParser().parse(s);
When I execute, it will give me the exception java.lang.String cannot be cast to org.json.simple.JSONObject
But when I hard code json directly like below its working fine. Wat could be the reason?
JSONObject json = (JSONObject)new JSONParser().parse("{\"application\":\"admin\",\"keytype\":\"PRODUCTION\",\"callbackUrl\":\"qwerewqr;ewqrwerq;qwerqwerq\",\"authorizedDomains\":\"ALL\",\"validityTime\":\"3600000\",\"retryAfterFailure\":true}");
UPDATE
When I print s, it will give me the output below:
"{\"application\":\"admin\",\"keytype\":\"PRODUCTION\",\"callbackUrl\":\"qwerewqr;ewqrwerq;qwerqwerq\",\"authorizedDomains\":\"ALL\",\"validityTime\":\"3600000\",\"retryAfterFailure\":true}"
I ran this through eclipse by providing arguments in run configuration.
public static void main(String[] args) {
String s = args[0].toString();
System.out.println("=>" + s);
try {
JSONObject json = (JSONObject) new JSONParser().parse(s);
System.out.println(json);
} catch (ParseException e) {
e.printStackTrace();
}
}
Output
=>{"application":"admin","keytype":"PRODUCTION","callbackUrl":"qwerewqr;ewqrwerq;qwerqwerq","authorizedDomains":"ALL","validityTime":"3600000","retryAfterFailure":true}
{"validityTime":"3600000","callbackUrl":"qwerewqr;ewqrwerq;qwerqwerq","application":"admin","retryAfterFailure":true,"authorizedDomains":"ALL","keytype":"PRODUCTION"}
Make sure that the string is a valid JSON. You can user JSONObject parameterized constructor with the given string to convert the JSON string to a valid JSON object.
For example,
try {
String jsonString = " {'application':'admin','keytype':'PRODUCTION','callbackUrl':'qwerewqr;ewqrwerq;qwerqwerq','authorizedDomains':'ALL','validityTime':3600000,'retryAfterFailure':true}";
JSONObject data = new JSONObject(jsonString);
String application = data.getString("application"); //gives admin
String keytype = data.getString("keytype"); //gives PRODUCTION
} catch (JSONException e) {
e.printStackTrace();
}
I had the same issue
package com.test;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JSONTest {
public static void main(String[] args) {
String s = args[0];
try {
JSONObject json = new JSONObject((String) new JSONParser().parse(s));
System.out.println(json);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
This worked for me
Try this
package com.test;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JSONTest {
public static void main(String[] args) {
String s = args[0];
try {
JSONObject json = (JSONObject) new JSONParser().parse(s);
System.out.println(json);
} catch (ParseException e) {
e.printStackTrace();
}
}
Then on command line
java -classpath ".;json-simple-1.1.1.jar" com.test.JSONTest {\"application\":\"admin\",\"keytype\":\"PRODUCTION\",\"callbackUrl\":\"qwerewqr;ewqrwerq;qwerqwerq\",\"authorizedDomains\":\"ALL\",\"validityTime\":\"3600000\",\"retryAfterFailure\":true}
The out put is
{"validityTime":"3600000","callbackUrl":"qwerewqr;ewqrwerq;qwerqwerq","application":"admin","retryAfterFailure":true,"authorizedDomains":"ALL","keytype":"PRODUCTION"}

Accessing JSON property name using java

I'm working on a way to parse JSON files and collect their contents for use elsewhere. I currently have a working example that is as follows:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class testJSONParser {
public static void main(String[] args) throws Exception {
List<Map<String, String>> jsonArray = new ArrayList<Map<String, String>>();
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
try {
String line = br.readLine();
while (line != null) {
JSONObject jsonObject = (JSONObject)new JSONParser().parse(line);
Map<String, String> currentLineMap = new HashMap<String, String>();
currentLineMap.put("country", jsonObject.get("country").toString());
currentLineMap.put("size", jsonObject.get("size").toString());
currentLineMap.put("capital", jsonObject.get("capital").toString());
jsonArray.add(currentLineMap);
line = br.readLine();
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
};
}
}
}
I'm using the json simple library for parsing the passed in JSON strings.
Here's a sample string from the parsed file.
{"**country**":"Canada","**size**":"9,564,380","**capital**":"Ottawa"}
What my question is about is how to take this code, and have the put method be able to assign to the corresponding Map dynamically. This is what I currently have:
for (int i = 0; i < jsonObject.size(); i++) {
currentLineMap.put(jsonObject.???.toString(), jsonObject.get(i).toString());
}
The ??? part is where I'm stumped. Getting the values of the current JSON line is easy enough. But how to get the property values (highlighted in bold in the JSON string sample) eludes me. Is there a method that I can call on this object that I'm not familiar with? A different and better way to itenerate through this? Or am I doing this completely assbackwards right from the get go?
In the JSON.org reference implementation, you could do:
for (String key : JSONObject.getNames(jsonObject))
{
map.put(key, jsonObject.get(key));
}
In JSON simple, you would do:
for (Object keyObject : jsonObject.keySet())
{
String key = (String)keyObject;
map.put(key, (String)jsonObject.get(key));
}
This should do the trick.

Categories