Parsing json object into a string - java

I have a question regarding a web-application I'm building where I have a REST service receiving a json string.
The Json string is something like:
{
"string" : "value",
"string" : "value",
"object" : {
"string" : "value",
"string" : "value",
....
}
}
I'm using resteasy to parse the json string which uses jackson underneath. I have a jaxb annotated class and I want to parse the "object" entirely into a String variable. The reason I want to do this is to be able to parse the json later using the correct parser (it depends on the application that sends the request so it is impossible to know in advance).
My jaxb annotated class looks like this:
#XmlRootElement
#XmlAccessorType(XmlAccessType.PROPERTY)
public class Test{
#XmlElement(type = String.class)
private String object;
//getter and setter
...
}
When I execute the rest call and let jackson parse this code I get an
Can not deserialize instance of java.lang.String out of START_OBJECT token
error. So actually I'm trying to parse a piece of a json string, which is a json object, into a String. I can't seem to find someone with a similar problem.
Thanks in advance for any response.

java.lang.String out of START_OBJECT token
this means that expected character after "object" is quotes ", but not brackets {.
Expected json
"object" : "my object"
Actual json
"object" : { ...
=======
If you want parse json like in your example, then change your class. E.g.
#XmlRootElement
#XmlAccessorType(XmlAccessType.PROPERTY)
public class Test{
#XmlElement
private InnerTest object;
//getter and setter
...
}
#XmlAccessorType(XmlAccessType.PROPERTY)
public class InnerTest{
#XmlElement
private String string;
//getter and setter
...
}

If I understand this question you just want a mechnanism, that converts a Java-Object into a JSON-String and the other way.
I needed this as well, while I was using a WebSocket Client-Server communication where a JSON String has been passed around.
For this I used GSON (see GSON). There you got the possibility to create a complete JSON-String.
Here some example:
// Converts a object into a JSON-String
public String convertMyClassObjectToJsonFormat() {
MyClass myObject = new MyClass();
Gson gson = new Gson();
return gson.toJson(myObject);
}
//Converts a JSON-String into a Java-Class-Object
public MyClass convertJsonToMyClassObject(
CharBuffer jsonMessage) {
Gson gson = new Gson();
return gson.fromJson(jsonMessage.toString(),
MyClass.class);
}
What you need is, that you your Class-Attributes-setter and JSON-Attribute-names are equivalent. E.g.
{
"info":[
{
"name": "Adam",
"address": "Park Street"
}
]
}
Your Class should look like this:
public class Info{
private String name;
private String address;
public void setName(String name){
this.name = name;
}
public void setAddress(String address){
this.address = address;
}
}

#KwintenP Try using the json smart library.
You can then simply retrieve the JSON object first using:
JSONObject test = (JSONObject) JSONValue.parse(yourJSONObject);
String TestString = test.toString();
What's more, you can retrieve a specific object inside a JSON object may it be another object, an array and convert it to a String or manipulate the way you want.

you also can do something like this ;
public class LeaderboardView
{
#NotEmpty
#JsonProperty
private String appId;
#NotEmpty
#JsonProperty
private String userId;
#JsonProperty
private String name = "";
#JsonProperty
private String imagePath = "";
#NotEmpty
#JsonIgnore
private String rank = "";
#NotEmpty
#JsonProperty
private String score;
public LeaderboardView()
{
// Jackson deserialization
}
}

Related

Mapping multiple simple JSON fields to complex POJO with Jackson

I am trying to map a JSON structure to a specific POJO that doesn't really match the JSOM, here is a simple example:
JSON
{
"strA": "MyStr",
"Street": "1st Lane",
"Number": "123"
}
POJO
#JsonIgnoreProperties(ignoreUnknown = true)
public class ClassA {
#JsonProperty("strA")
private String strA;
private Address address;
//Constructor, getter,setter
#JsonRootName("Address")
#JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
private String address;
public Address() {
}
public String getAddress() {
return address;
}
#JsonAnySetter
public void setAddress(#JsonProperty("Street") String street, #JsonProperty("Number")String number) {
this.address = number + " " + street;
}
}
Now, Address is properly created from the sample JSON (only made it work with the JsonAnySetter unfortunately), but I can't get ClassA to be created properly.
I've tried annotating the Address property of it, but to no avail.
How can I achieve this in a "simple" way? This is important as this example is simple, but my real use cases involves several composed classes that need information from the JSON root + from complex JSON elements with different names.
Thank you for your time.

Convert Java object with embedded objects to a JSON with list of attributes and list of values and vice versa

In my Spring project I have several objects that should be serialized to a specific JSON format.
public class Person {
private Integer id;
private String name;
private String height;
private Address address;
}
and
public class Address {
private String street;
private String city;
private String phone;
}
Let assume that Person.height and Address.phone should not appear in the JSON.
The resulting JSON should look like
{
"attributes": ["id", "name", "street", "city"],
"values": [12345, "Mr. Smith", "Main street", "Chicago"]
}
I can create create a standard JSON with an ObjectMapper and some annotations like #JsonProperty and #JsonUnwrapped where I disable some SerializationFeatures. But at the moment I'm not able to create such a JSON.
Is there an easy way to create this JSON? And how would the way back (deserialization) look like?
There are good reasons Jackson doesn't serializes maps in this format. It's less readable and also harder to deserialize properly.
But if you just create another POJO it's very easy to achieve what you want to do:
public class AttributeList {
public static AttributeList from(Object o) {
return from(new ObjectMapper().convertValue(o, new TypeReference<Map<String, Object>>() {}));
}
public static AttributeList from(Map<String, Object> attributes) {
return new AttributeList(attributes);
}
private final List<String> attributes;
private final List<Object> values;
private AttributeList(Map<String, Object> o) {
attributes = new ArrayList<>(o.keySet());
values = new ArrayList<>(o.values());
}
}

Ignore json POJO fields not mapped in object in spring boot

I have pojo which has many fields. I have set value some field. But when i create json, whole pojo create a json . here is the code i have used:
Pojo
public class BasicInfoModel {
private String client_id="";
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
Repository code
public BasicInfoModel getBasicInfo() {
BasicInfoModel lm = new BasicInfoModel();
lm.setFather_name("Enamul Haque");
return lm;
}
Controller code
#RequestMapping(value = "/get_donar_basic_info", method = RequestMethod.POST, produces ="application/json")
public #ResponseBody BasicInfoModel getBasicinfo(){
return repository.getBasicInfo();
}
But my json is resposne like bellow:
{
"client_id": "",
"father_name": "Enamul Haque",
"mother_name": "",
"gendar": ""
}
I have set value to father_name but i have seen that i have found all the value of pojo fields. I want get only set value of father_name and ignor other value which is not set in repository.
My json look like bellow: I will display only father_name.how to display bellow like json from above code?
{
"father_name": "Enamul Haque"
}
Please help me..
Json include non null values to ignore null fields when serializing a java class
#JsonInclude(Include.NON_NULL)
Jackson allows controlling this behavior at either the class level:
#JsonInclude(Include.NON_NULL)
public class BasicInfoModel { ... }
at the field level:
public class BasicInfoModel {
private String client_id="";
#JsonInclude(Include.NON_NULL)
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
from jackson 2.0 use here use
#JsonInclude(JsonInclude.Include.NON_NULL)
You can also ignore the empty values
#JsonInclude(JsonInclude.Include.NON_EMPTY)
Add the #JsonIgnoreProperties("fieldname") annotation to your POJO.
Or you can use #JsonIgnore before the name of the field you want to ignore while deserializing JSON. Example:
#JsonIgnore
#JsonProperty(value = "client_id")
#RequestMapping(value = "/get_donar_basic_info", method = RequestMethod.POST, produces ="application/json")
public #ResponseBody BasicInfoModel getBasicinfo(){
return repository.getBasicInfo();
}
You can ignore field at class level by using #JsonIgnoreProperties annotation and specifying the fields by name:
#JsonIgnoreProperties(value = { "client_id" })
public class BasicInfoModel {
private String client_id="";
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
Or you can use #JsonIgnore annotation directly on the field.
public class BasicInfoModel {
#JsonIgnore
private String client_id="";
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
You can read here more about this.

How to display class as a JSON response in Java?

Currently I'm working on spring project and I want to display class as a JSON response. Following is the class template and other related details.
public class Country {
#Column(name = "name")
private String name;
#Id
#Column(name = "code")
private String Code;
//Getters & Setters ...
}
current response :
[{"name":"Andorra","code":"AD"},{"name":"United Arab Emirates","code":"AE"}]
Expected response :
[ { "countries" : [{"name":"Andorra","code":"AD"},{"name":"United Arab Emirates","code":"AE"}], "status" : "ok", "message":"success", etc..etc...}]
instead of status and message, it could be some array list too.
You need create class contain list and use ResponseEntity.
public class Foo {
private List<Country> countries;
// get/set...
}
#Controller
public class MyController {
#ResponseBody
#RequestMapping(value = "/foo", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public ResponseEntity<Foo> foo() {
Foo foo = new Foo();
Country country = new Country();
foo.getCountries().add(country);
return ResponseEntity.ok(foo);
}
}
You should create another object, e.g. called Countries as shown below:
public class Countries {
private List<Country> countries;
// getters & setters
}
or:
public class Countries {
private Country[] countries;
// getters & setters
}
The list or array of Country objects will map to your expected {"countries" : [{"name":"Andorra","code":"AD"},{"name":"United Arab Emirates","code":"AE"}]}, because the JSON {} refers to some object and [] refers to list/array in Java code.
Actually you can also achieve using jackson library.
//Create obj of ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//Get the Json string value from the mapper
String json = mapper.writeValueAsString(obj)
And then return this json string in your controller method.
The advantage of using this is that, you can also ignore certain fields in the POJO for JSON conversion using #JsonIgnore annotation (Put this annotation before the getter of the field that you want to ignore) (Not sure if you can do the same from Spring ResponseEntity.
Note: Please correct me if I am wrong anywhere.

JSON deserialization issue with jackson

I have a json object like this
{
"id":23 ,
"key": "AKEY",
"description": {
"plain": {
"value": "This is an example",
"representation": "plain"
}
}
}
I'd like to map it to this object
public class JsonResponse {
private int id;
private String key;
private String name;
private String type;
private String description;
/*usual getters and setters*/
}
I use the JSONSerialiser like this
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(responseEntity);
But how do I map the "description.plain.value" to "JsonResponse.description"?
Can this be done using jackson annotations?
thanks for your help
I found this post Binding JSON child object property into Java object field in Jackson that partially solved my problem.
I wrote two setDescription() methods, one used by myself in my code, and one that's been called by jacskon
#JsonProperty(value = "description")
public void setDescription(Map<String, Map<String,String>> description) {
this.description = description.get("plain").get("value");
}
public void setDescription(String description) {
this.description = description;
}
It looks like the JsonProperty annotation is required to make jackson use the right setter.
Still I'm ok with this as long as it is a "short nested" property, but I guess Beri response is more acceptable with complex JSON responses.

Categories

Resources