How to Convert JSON to JAVA Object using ObjectMapper? - java

Java Object
class B {
private String attr;
/***** getters and setters *****/
}
class A {
private String attr1;
private String attr2;
private Map<String,B> attr3;
/***** getters and setters *****/
}
Json Object
json = {attr1 :"val1", attr2 : "val2", attr3 : {attr : "val"}}
How to convert json to java Object (class java contain Map as type of attribute) ?

You can use Jackson to do that:
//Create mapper instance
ObjectMapper mapper = new ObjectMapper();
//Usea a JSON string (exists other methos, i.e. you can get the JSON from a file)
String jsonString= "{'name' : 'test'}";
//JSON from String to Object
MyClass result= mapper.readValue(jsonString, MyClass .class);

You can use Gson library as following:
// representation string for your Json object
String json = "{\"attr1\": \"val1\",\"attr2\": \"val2\",\"attr3\": {\"attr\": \"val\"}}";
Gson gson = new Gson();
A a = gson.fromJson(json, A.class);

Create a model/POJO which resembles your json structure and then by putting json string in json file you can get java object by using below simple code by using JACKSON dependacy
ObjectMapper mapper = new ObjectMapper();
File inRulesFile = (new ClassPathResource(rulesFileName + ".json")).getFile();
List<Rule> rules = mapper.readValue(inRulesFile, new TypeReference<List<Rule>>() {
});

#RunWith(SpringRunner.class)
#SpringBootTest
class PostSaveServiceTest {
private static final String PATH_TO_JSON = "classpath:json/post-save";
private static final String EXTENSION_JSON = ".json";
#Test
void setData() {
ObjectMapper objectMapper = new ObjectMapper();
Post post = runParseJsonFile(objectMapper);
System.out.println(post);
}
private Post runParseJsonFile(ObjectMapper objectMapper) {
File pathToFileJson = getPathToFileJson(PATH_TO_JSON + EXTENSION_JSON);
Post post = null;
try {
post = objectMapper.readValue(pathToFileJson, Post.class);
} catch (IOException e) {
System.out.println("File didn't found : " + e);
}
return post;
}
private File getPathToFileJson(String path) {
File pathToJson = null;
try {
pathToJson = ResourceUtils.getFile(path);
} catch (IOException e) {
e.printStackTrace();
}
return pathToJson;
}
}

Related

How to parse nested json object as it is using Jackson

I have the following JSON structure:
{
"sets": [
{...},
{
"id": "id",
"html": "<html></html>",
"javascript": "{onError: function (event) {}}",
"css": ".someclass {}",
"translations": {
"en": { "LABEL_1": "Some label text", "HEADER_1": "Some header text" },
"fr": { "LABEL_1": "Some label text", "HEADER_1": "Some header text" }
}
}
]
}
I have an object that represents this JSON for deserialization purpose
#Data //Lombok
#NoArgsConstructor //Lombok
public class Set {
#JsonProperty("screenSetID")
private String screenSetID;
#JsonProperty("html")
private String html;
#JsonProperty("css")
private String css;
#JsonProperty("javascript")
private String javascript;
#JsonProperty("translations")
private String translations;
}
I have the following piece of code to deserialize JSON
private List<Set> parseSetsData(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, TypeReference<List<Set>(){});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
How I can parse translations JSON object as it is?
Any Jason object could be mapped to Map<String, Object> and any Json List could be mapped to List<Object>. So you could parse your JSON as follows:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModules(new JavaTimeModule());
objectReader = objectMapper.reader();
Map<String, Object> parsedJson = (Map<String, Object>)objectReader.forType(Map.class).readValue(jsonString)
Note that your JSON is a JSON object and not JSON list, so this example parses it to Map
I'm sure you understand that the that you want is part of on array hats why I had to use a for loop:
ObjectMapper mapper = new ObjectMapper();
JsonNode treeNode = mapper.readTree(json);
treeNode=treeNode.findValue("sets");
for (Iterator<JsonNode> it = treeNode.elements(); it.hasNext(); ) {
JsonNode node = it.next();
String theValueYouWant=node.findValue("translations").textValue();
}
Json I found that when you deserialize your item it should look like the following;
public class En
{
#JsonProperty("LABEL_1")
public String lABEL_1;
#JsonProperty("HEADER_1")
public String hEADER_1;
}
public class Fr
{
#JsonProperty("LABEL_1")
public String lABEL_1;
#JsonProperty("HEADER_1")
public String hEADER_1;
}
public class Translations
{
public En en;
public Fr fr;
}
public class Set
{
public String id;
public String html;
public String javascript;
public String css;
public Translations translations;
}
However, in your class, "translations" is a string, but in a JSON structure, it points to an object.

How parse nested escaped json with Jackson?

Consider json:
{
"name": "myName",
"myNestedJson": "{\"key\":\"value\"}"
}
Should be parsed into classes:
public class MyDto {
String name;
Attributes myNestedJson;
}
public class Attributes {
String key;
}
Can it be parsed without writing stream parser? (Note that myNestedJson contains json escaped json string)
I think you can add a constructor to Attributes that takes a String
class Attributes {
String key;
public Attributes() {}
public Attributes(String s) {
// Here, s is {"key":"value"} you can parse it into an Attributes
// (this will use the no-arg constructor)
try {
ObjectMapper objectMapper = new ObjectMapper();
Attributes a = objectMapper.readValue(s, Attributes.class);
this.key = a.key;
} catch(Exception e) {/*handle that*/}
}
// GETTERS/SETTERS
}
Then you can parse it this way:
ObjectMapper objectMapper = new ObjectMapper();
MyDto myDto = objectMapper.readValue(json, MyDto.class);
This is a little dirty but your original JSON is too :)

Can not deserialize instance of Object out of START_ARRAY token

I have two object one is Dashboard and second is Room i have a json which is look like this
{
"hotel_id":"1",
"hotel_room":"200",
"hotel_properties":[{
"id":"1",
"room_type":"Single",
"rack_rate":"2000",
"publish_rate":"1800",
"discount":"10",
"availiable":"40",
"total":"50"
},
{
"id":"2",
"room_type":"Double",
"rack_rate":"4000",
"publish_rate":"3600",
"discount":"10",
"availiable":"45",
"total":"50"
}
]
}
And the Object is
public class DashBoard {
private int hotel_id;
private int hotel_room;
#JsonProperty("hotel_properties")
private Room hotel_properties;
}
There is another Object Room which is look like this
public class Room {
private Long id;
private String room_type;
private String rack_rate;
private String publish_rate;
private String discount;
private String availiable;
private String total;
}
I am Hide all constructor,setter and getter for Stackoverflow but it is in my code
i want parse Json to Object using ObjectMapper from an URL using this code
JsonReader jsonReader = new JsonReader();
ObjectMapper mapper = new ObjectMapper();
try {
JSONObject json = jsonReader.readJsonFromUrl("http://localhost/quinchy/json/dashboard.json");
DashBoard dsh = mapper.readValue(json.toString(), DashBoard.class);
System.out.println(json.toString());
} catch (IOException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but i get this error
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of Object out of START_ARRAY token
please help me out from this
From the JSON String you posted, it looks like there is a list of Room objects. But you have used a single object.
In your DashBoard class, try changing:
private Room hotel_properties;
to:
private List<Room> hotel_properties;

How to generate Json with Java

I am working on an application where i have to generate a json like this:
[
{"title":"Culture","start":"Salary","end":"Work"},
{"title":"Work","start":"Salary","end":"Work"}
]
But my code generates json like this:
{{"name":"Culture"},[{"name":"Salary"},{"name":"Work"}],}
My code:
public class ParseJson {
public static class EntryListContainer {
public List<Entry> children = new ArrayList<Entry>();
public Entry name;
}
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
}
public static void main(String[] args) {
EntryListContainer elc1 = new EntryListContainer();
elc1.name = new Entry("Culture");
elc1.children.add(new Entry("Salary"));
elc1.children.add(new Entry("Work"));
ArrayList<EntryListContainer> al = new ArrayList<EntryListContainer>();
Gson g = new Gson();
al.add(elc1);
StringBuilder sb = new StringBuilder("{");
for (EntryListContainer elc : al) {
sb.append(g.toJson(elc.name));
sb.append(",");
sb.append(g.toJson(elc.children));
sb.append(",");
}
String partialJson = sb.toString();
if (al.size() > 1) {
int c = partialJson.lastIndexOf(",");
partialJson = partialJson.substring(0, c);
}
String finalJson = partialJson + "}";
System.out.println(finalJson);
}
}
Can anyone help me to generate this json in my required format ?? please thanks in advance
Try this
public class Entry {
public String title;
public String start;
public String end;
}
And in another part of your code
private ArrayList<Entry> entries = new ArrayList<>();
// Fill the entries...
String the_json = new Gson().toJson(entries);
1) First Create your POJO
public class MyJSONObject {
private String title;
private String start;
private String end;
//getter and setter methods
[...]
#Override
public String toString() {
}
}
2) Use com.google.code.gson library
public static void main(String[] args) {
{
ArrayList<MyJSONObject> myJSONArray = new ArrayList<>();
MyJSONObject obj = new MyJSONObject();
obj.setTitle="Culture";
obj.set[...]
myJSONArray.add(obj);
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(myJSONArray);
System.out.println(json);
}
Output : [{"title":"Culture","start":"Salary","end":"Work"}, ...]
I recommend you to use some JSON Java API, like Gson. It's very simple to generate a string json from a POJO object or to create a POJO object from a string json.
The code for generating a string json from a POJO object is like this:
Gson gson = new Gson();
String stringJson = gson.toJson(somePojoObject);
The code for creating a POJO object from a string json is like this:
Gson gson = new Gson();
SomePojoClass object = gson.fromJson(stringJson, SomePojoClass.class);
Note that you can not serialize objects with circular references. This causes infinite recursion.

Converting Java objects to JSON with Jackson

I want my JSON to look like this:
{
"information": [{
"timestamp": "xxxx",
"feature": "xxxx",
"ean": 1234,
"data": "xxxx"
}, {
"timestamp": "yyy",
"feature": "yyy",
"ean": 12345,
"data": "yyy"
}]
}
Code so far:
import java.util.List;
public class ValueData {
private List<ValueItems> information;
public ValueData(){
}
public List<ValueItems> getInformation() {
return information;
}
public void setInformation(List<ValueItems> information) {
this.information = information;
}
#Override
public String toString() {
return String.format("{information:%s}", information);
}
}
and
public class ValueItems {
private String timestamp;
private String feature;
private int ean;
private String data;
public ValueItems(){
}
public ValueItems(String timestamp, String feature, int ean, String data){
this.timestamp = timestamp;
this.feature = feature;
this.ean = ean;
this.data = data;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
public int getEan() {
return ean;
}
public void setEan(int ean) {
this.ean = ean;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
#Override
public String toString() {
return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);
}
}
I just missing the part how I can convert the Java object to JSON with Jackson:
public static void main(String[] args) {
// CONVERT THE JAVA OBJECT TO JSON HERE
System.out.println(json);
}
My Question is: Are my classes correct? Which instance do I have to call and how that I can achieve this JSON output?
To convert your object in JSON with Jackson:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.
I used a third-party library to aid in the endeavor: org.codehaus.jackson
All of the downloads for this can be found here.
For base JSON functionality, you need to add the following jars to your project's libraries:
jackson-mapper-asl
and
jackson-core-asl
Choose the version your project needs. (Typically you can go with the latest stable build).
Once they are imported in to your project's libraries, add the following import lines to your code:
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service
User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "sampleU#example.com";
ObjectMapper mapper = new ObjectMapper();
try {
// convert user object to json string and return it
return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException e) {
// catch various errors
e.printStackTrace();
}
The result should looks like this:
{"firstName":"Sample","lastName":"User","email":"sampleU#example.com"}
Just follow any of these:
For jackson it should work:
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
//will return json in string
For gson it should work:
Gson gson = new Gson();
return Response.ok(gson.toJson(yourClass)).build();
You could do this:
String json = new ObjectMapper().writeValueAsString(yourObjectHere);
This might be useful:
objectMapper.writeValue(new File("c:\\employee.json"), employee);
// display to console
Object json = objectMapper.readValue(
objectMapper.writeValueAsString(employee), Object.class);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(json));
You can use Google Gson like this
UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);
Gson gson = new Gson();
String jsonStr = gson.toJson(user);
Well, even the accepted answer does not exactly output what op has asked for. It outputs the JSON string but with " characters escaped. So, although might be a little late, I am answering hopeing it will help people! Here is how I do it:
StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());
Note: To make the most voted solution work, attributes in the POJO have to be public or have a public getter/setter:
By default, Jackson 2 will only work with fields that are either
public, or have a public getter method – serializing an entity that
has all fields private or package private will fail.
Not tested yet, but I believe that this rule also applies for other JSON libs like google Gson.
public class JSONConvector {
public static String toJSON(Object object) throws JSONException, IllegalAccessException {
String str = "";
Class c = object.getClass();
JSONObject jsonObject = new JSONObject();
for (Field field : c.getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
String value = String.valueOf(field.get(object));
jsonObject.put(name, value);
}
System.out.println(jsonObject.toString());
return jsonObject.toString();
}
public static String toJSON(List list ) throws JSONException, IllegalAccessException {
JSONArray jsonArray = new JSONArray();
for (Object i : list) {
String jstr = toJSON(i);
JSONObject jsonObject = new JSONObject(jstr);
jsonArray.put(jsonArray);
}
return jsonArray.toString();
}
}

Categories

Resources