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.
Related
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();
}
}
}
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.
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"}
i need to convert a POJO to a JSONObject (org.json.JSONObject)
I know how to convert it to a file:
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(file.toString()), registrationData);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But I dont want a file this time.
If we are parsing all model classes of server in GSON format then this is a best way to convert java object to JSONObject.In below code SampleObject is a java object which gets converted to the JSONObject.
SampleObject mSampleObject = new SampleObject();
String jsonInString = new Gson().toJson(mSampleObject);
JSONObject mJSONObject = new JSONObject(jsonInString);
If it's not a too complex object, you can do it yourself, without any libraries. Here is an example how:
public class DemoObject {
private int mSomeInt;
private String mSomeString;
public DemoObject(int i, String s) {
mSomeInt = i;
mSomeString = s;
}
//... other stuff
public JSONObject toJSON() {
JSONObject jo = new JSONObject();
jo.put("integer", mSomeInt);
jo.put("string", mSomeString);
return jo;
}
}
In code:
DemoObject demo = new DemoObject(10, "string");
JSONObject jo = demo.toJSON();
Of course you can also use Google Gson for more complex stuff and a less cumbersome implementation if you don't mind the extra dependency.
The example below was pretty much lifted from mkyongs tutorial. Instead of saving to a file you can just use the String json as a json representation of your POJO.
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
YourObject obj = new YourOBject();
Gson gson = new Gson();
String json = gson.toJson(obj); //convert
System.out.println(json);
}
}
Here is an easy way to convert Java object to JSON Object (not Json String)
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.simple.parser.JSONParser;
JSONObject jsonObject = (JSONObject) JSONValue.parse(new ObjectMapper().writeValueAsString(JavaObject));
How to get JsonElement from Object:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
final ObjectMapper objectMapper = new ObjectMapper();
final Gson gson = new Gson();
String json = objectMapper.writeValueAsString(source);
JsonElement result = gson.fromJson(json, JsonElement.class);
I am trying to pass a JSON request to my server where the controller encounters an error while converting the JSON to POJO.
JSON Request
{
"request":[
{"name":"mac"},
{"name":"rosy"}
]
}
My controller function
#RequestMapping(value = "/namelist",
method = RequestMethod.POST,
consumes = { "application/json" },
produces = {"application/json"})
public ... postNameList(#RequestBody NameList names) {}
Public Class NameList extends ArrayList<Name> {}
Public Class Name { private name; ...}
Error
message: "Could not read JSON: Can not deserialize instance of
com.abc.xyz.mypackage.NameList out of START_OBJECT token at [Source:
org.eclipse.jetty.server.HttpConnection$Input#79aac24b{HttpChannelOverHttp#1d109942{r=1,a=DISPATCHED,uri=/namelist},HttpConnection#2cbdcaf6{FILLING},g=HttpGenerator{s=START},p=HttpParser{s=END,137
of 137}}; line: 1, column: 1]
I am not sure what's wrong with the code. I am fairly new to Spring so any help is appreciated.
Your POJO classes should look like this:
class Request {
private List<Name> request;
// getters, setters, toString, ...
}
class Name {
private String name;
// getters, setters, toString, ...
}
Usage:
#RequestMapping(value = "/namelist",
method = RequestMethod.POST,
consumes = { "application/json" },
produces = {"application/json"})
public ... postNameList(#RequestBody Request request) { ... }
I faced similar situation and then created utility to convert JSON objects into Java Objects. Hope this helps.
Here sample.json is the file you want to a Java Object
import com.sun.codemodel.JCodeModel;
import org.jsonschema2pojo.*;
import org.jsonschema2pojo.rules.RuleFactory;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
/**
* Created by Pratik Ambani
*/
class JsonToPojo {
public static void main(String[] args) {
String packageName = "com.practise";
File inputJson = null;
try {
inputJson = ResourceUtils.getFile("classpath:sample.json");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File outputPojoDirectory = new File("." + File.separator + "Generated Pojo");
outputPojoDirectory.mkdirs();
try {
new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
} catch (IOException e) {
System.err.println("Encountered issue while converting to pojo: " + e.getMessage());
e.printStackTrace();
}
}
private void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException {
JCodeModel codeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() {
#Override
public boolean isGenerateBuilders() { // set config option by overriding method
return true;
}
#Override
public SourceType getSourceType() {
return SourceType.JSON;
}
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(codeModel, className, packageName, inputJson);
codeModel.build(outputPojoDirectory);
}
}