Remove special characters from JSON output - java

How to remove special character (In here '#') in the rest API output when converting to Java object.Because it is not allowed in java variables.
{
"#id" : "1234" ,
"dateTime" : "2022-05-27T10:15:00Z" ,
"measure" : "abcd" ,
"value" : 1.609
}
Below object is not allowed:
private String #id;
private String dateTime;
private String measure;
private float value;
// Getter Methods
public String get #id() {
return #id;
}

Depending on which JSON parser you're using, you can specify the JSON name for a given field. Here is an example for Jackson and GSON
public class TestClass {
#SerializedName("#id") // GSON
#JsonProperty("#id") // Jackson
private String id;
private String dateTime;
private String measure;
private float value;
// Getters & Setters
}

Related

How to set a handler for binding JSON fields which has a variety of naming styles to a POJO

I'm using Springboot 2.5.1, Jackson 2.13.1
Input JSON looks like:
{
"hello_word": "you are welcome",
"my-name": "Meow",
"Age": 11
}
Java POJO:
#Data
class A {
private String helloWorld;
private String myName;
private Integer age;
}
Expected binding result:
class A {
private String helloWorld = "you are welcome";
private String myName = "Meow";
private Integer age = 11;
}
As you can see, there are 3 naming styles in the JSON.
I want to ask is there any way to set a handler or a subclass that can bind values correctly to POJO's fields in this case.
You can use #JsonProperty, for more examples
#Data
class A {
#JsonProperty("hello_word")
private String helloWorld;
#JsonProperty("my-name")
private String myName;
#JsonProperty("Age")
private Integer age;
}

GSON not parsing nested JSON objects properly

I have some data in the form of JSON, and was using the GSON library to parse it into a Java object to be used in later portions of the code. The JSON has nested objects, which don't seem to be getting parsed properly, and I can't figure out why, as the outer object is being converted as desired. Here is an example of the JSON data I'm looking at:
{
"title":"Emergency Services Headquarters",
"description":"",
"cid":"C70856",
"building_id":"4714",
"building_number":"3542",
"campus_code":"20",
"campus_name":"Busch",
"location":{
"name":"Emergency Services Headquarters",
"street":"129 DAVIDSON ROAD",
"additional":"",
"city":"Piscataway",
"state":"New Jersey",
"state_abbr":"NJ",
"postal_code":"08854-8064",
"country":"United States",
"country_abbr":"US",
"latitude":"40.526306",
"longitude":"-74.461470"
},
"offices":[
"Emergency Services"
]
}
I used codebeautify to create the Java object classes required for the JSON (everything is within Building.java):
public class Building {
private String title;
private String description;
private String cid;
private String building_id;
private String building_number;
private String campus_code;
private String campus_name;
Location LocationObject;
ArrayList < Object > offices = new ArrayList < Object > ();
//Setters and getters have been omitted
}
class Location {
private String name;
private String street;
private String additional;
private String city;
private String state;
private String state_abbr;
private String postal_code;
private String country;
private String country_abbr;
private String latitude;
private String longitude;
//Setters and getters have been omitted
}
Here is the code I'm using to parse the JSON, where the variable json is an input parameter for the method:
Gson obj = new Gson();
JsonArray buildingsArray = new JsonArray();
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(json);
buildingsArray = jsonElement.getAsJsonArray();
for (int i = 0; i < buildingsArray.size(); i++)
Building building = obj.fromJson(buildingsArray.get(i), Building.class);
When I call methods such as building.getTitle() or building.getCid(), I get the appropriate values, however when I do building.getLocation() (where Location is a separate object), the code returns null. I have not been able to figure it out, is it an issue with the way GSON works? Or am I doing something wrong in my code?
First of all, change:
Location LocationObject;
to:
private Location location;
And, you can deserialise JSON much easier:
Gson gson = new GsonBuilder().create();
Building building = gson.fromJson(json, Building.class);
Json property name should match your POJO class properties, it should be location not LocationObject
public class Building {
private String title;
private String description;
private String cid;
private String building_id;
private String building_number;
private String campus_code;
private String campus_name;
Location location;
ArrayList < Object > offices = new ArrayList < Object > ();
//Setters and getters have been omitted
}
It seems that you have a bad naming. Your location object in Building class is called LocationObject when your object inside JSON is called location.

How to deserialize JSON response using #JsonProperty?

I have this object which is converted into following format but it does not wrap it properly.
#JsonProperty("code")
private String code;
#JsonProperty("message")
private String msg;
#JsonProperty("assign")
private SomeVO someVO;
//getter, setters
to this format:
{
"status": {
"code": $value,
"message": $value
},
"data":{
"assign" {
"schemaLayoutFileName" : $value
"dataStoreTargetLocationText" : $value
}
}
}
How can it be done?
The class you have defined does not match the JSON you want to parse. Try the following design (if the class attributes names match the JSON properties names, you won't need #JsonProperty):
public class Foo {
private Status status;
private Data data;
// Getters and setters
}
public class Status {
private String code;
private String value;
// Getters and setters
}
public class Data {
private Assign assign;
// Getters and setters
}
public class Assign {
private String schemaLayoutFileName;
private String dataStoreTargetLocationText;
// Getters and setters
}

Gson to POJO, how to read the inner JSON Objects as part of the same POJO?

I have a JSON like below and would like to convert it using Gson to one POJO.
I am trying to figure out how to basically cut down the inner nested objects like desc to be treated as part of the same Java object, instead of creating a new POJO named Desc.
Is there a way to do this with Serialized Names to look into nested JSON objects?
Thanks in advance!
JSON to be converted to POJO
{
'name': name,
'desc': {
'country': country,
'city': city,
'postal': postal,
'street': street,
'substreet': substreet,
'year': year,
'sqm': sqm
},
'owner': [owner],
'manager': [manager],
'lease': {
'leasee': [
{
'userId': leaseeId,
'start': leaseeStart,
'end': leaseeeEnd
}
],
'expire': leaseExpire,
'percentIncrease': leasePercentIncrease,
'dueDate': dueDate
},
'deposit': {
'bank': 'Sample Bank',
'description': 'This is a bank'
}
}
Custom POJO
public class Asset {
private String mId;
#SerializedName("name")
private String mName;
private String mCountry;
private String mCity;
private String mPostal;
private String mStreet;
private String mSubstreet;
private int mYear;
private int mSqm;
#SerializedName("owner")
private List<String> mOwners;
#SerializedName("manager")
private List<String> mManagers;
private List<Leasee> mLeasees;
private DateTime mLeaseExpiration;
private int mPercentIncrease;
private int mDueDate;
private String mDepositBank;
private String mDepositDescription;
}

Parsing json object into a string

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
}
}

Categories

Resources