Create temporary Java object for JSON - java

What I want to do is create a temporary object on the fly so I can translate it to JSON and send it back to the JSP page for use by the JavaScript. FYI I'm using Java Jackson library to translate a Java Object into JSON.
The JavaBean Class for this object looks something like this.
public class MonthlyAnalysisBean {
private Date monthlyProcessDate;
private Double activeInventory;
private Double inactiveInventory;
private Double excessInventory;
/* Set... Get.... Bla bla methods */
}
I need an object that looks like this in JSON.
{
"date": "2014-04-04",
"Active": 100.00,
"Inactive": 10.23,
"Excess": 2.99
}
Basically I just need to nicely rename and format the same fields. Is there any way to do this In Java without creating another JavaBean and creating the new object?
It would be so easy in JavaScript to just create a new object, send the JSON and be off on our merry way.

Well if you don't want to "create another Javabean" Map<String, String> is an option.
You could just do
Map<String, String> map = new HashMap<String, String>();
map.put("date", monthlyAnalysisBean.getMonthlyProcessDate());
...
Or try to actually use Jackson using #JsonProperty
#JsonProperty("date")
public Date getMonthlyProcessDate() {
return monthlyProcessDate;
}

I've done sth like that with annotations from javax.xml.bind.annotation . I used wink library to marshal/unmarshal JAXB-annotated objects into JSON, but it's mostly for REST web services. I guess your Jackson should suite fine.
#XmlAttribute(name = "date")
private Date monthlyProcessDate;

Related

Java Spring omits fields when making a JSON

public class ConnectedEntry {
private EntryInScores scores;
private EntryInValues values;
private String someString;
public ConnectedEntry(EntryInScores scores, EntryInValues values) {
this.scores = scores;
this.values = values;
this.someString = "Adasd";
}
I have an object that looks more or less like this, and I use it as a GET response for my API. scores and values are both database entities. I wanted to add a String to the response with some additional information.
What happens is that the objects are properly turned into a JSON and they show up in the response, but the string is omitted, with no error: it's just not there.
I tried wrapping the string in a wrapper class, but it didn't help.
What could I do?
Usually Spring uses Jackson as the default converter from objects to JSON. In order for Jackson to convert to JSON you must provide getters, so that Jackson can get and convert those values. As I can see in your representation you don't have any getters. Try providing getters for the fields that you wish to convert. Never make fields public!
You can go for creating json object and put the data as key value pair to resolve this issue.
Happy Coding!!!

Change naming of attributes in json without #JsonProperty

I have to convert my json from camelCase to kebab-case.
Example:
My Json:
{
"disclaimerConfirmed" : true
}
And I need:
{
"disclaimer-confirmed" : true
}
I cannot use #JsonProperty because it rename this atributes permanently. I am looking for something which will consume Json (can be as String) and returns modified json(as String).
Jackson supports naming strategies so you could read the input String to map (with camelCase strategy) and then write the map back to a String (with kebab-case which is natively supported );
Specific method you need to switch these conventions in ObjectMapper without annotations is:
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.*);
You can have different serializers for different cases or you can create pojo with #JsonProperty and use those where-ever required.
For example,
class A {
private String disclaimerConfirmed;
}
class AkebabCase {
#JsonProperty("disclaimer-confirmed")
private String disclaimerConfirmed;
}
So, if you want to serialize to kebab-case you can use converters to convert A to AkebabCase and then serialize.

Object serialization to json, certain fields only

I have a large nested object. I want to serialise this object in the JSON string, however I need only certain fields to be included. Problem here is that fields could change very frequently and I want to build it in a way that could help me easy include or exclude fields for serialisation.
I know that I can write a lot of code to extract certain fields and build JSON "manually". But I wonder if there are any other elegant way to achieve similar outcome but specifying a list of required fields?
For example having following object structure I want include only id and name in the response:
class Building {
private List<Flat> flats;
}
class Flat {
private Integer id;
private Person owner;
}
class Person {
private String name;
private String surname;
}
Json:
{
"flats" : [
{
"flat":
{
"id" : "1",
"person" : {
"name" : "John"
}
}
}
]
}
You can use gson for serializing/deserializing JSON.
Then you can include the #Expose annotation to use only the fields you require.
Be sure to also configure your Gson object to only serialize "exposed" fields.
Gson gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Alternative:
You can actually do it the inverse way, marking fields which will not be exposed. You can do this with the transient keyword.
So whatever you want to ignore just add transient to it. Here's how it works on gson.
PS: This works on most Java JSON serializers too.
Using com.fasterxml.jackson.annotation.JsonIgnore is another way to achieve this.
import com.fasterxml.jackson.annotation.JsonIgnore;
class Person {
private String name;
#JsonIgnore
private String surname;
}
It will ignore the surname when the parser converts the bean to json.
Similar annotation will be available in other json processing libraries.
If using Gson, study how to use ExclusionStrategy & JsonSerializer.
Using those is a more flexible way to control serialization since it allows to decide per serialization what to serialize.
Using annotations requires later to add / remove those annotations from fields if there is a need to change what to serialize.
In the case of your example the latter might be more appropriate.
This question might be good startpoint
serialize-java-object-with-gson

Creating Map or Set using GSON

I am using Google's GSON library and want to create a JSON which looks something like this:
{
"teamSet":[],
"classificationMap" : {}
}
Notice that [] and {} are empty Set and Map respectively and are not surrounded with double quotes.
I want to create this Json using the GSON add/addproperty method and not by converting a Java class into JSON using the Gson.toJson() method. The business use-case restricts me from creating specific Java classes as the JSON structure may change overtime. So I cannot use a class like this as this would rigidly tie a JSON structure with a concrete class
class Linkage{
private Set<String> teamSet;
private Map<String, String> classificationMap;
// getter, setter methods follow
...
}
When I use the GSON.addproperty(genericObject, type), it is appending double quotes around [] and {}. I am using couchbase for my DB requirements and the double quotes around [] and {} makes couchbase treat them as string and not as Set/Map. This renders my Map-Reduce views useless and buggy :(
Please let me know if its possible to create such a JSON without having to tie it up with a concrete JAVA class. Thanks !
My current code looks like this:
// create types
Type setType = new TypeToken<Set<String>>() {}.getType();
Type mapType = new TypeToken<Map<String, String>>() {}.getType();
Gson GSON = new Gson();
Set<String> teams = new HashSet<String>();
Map<String, String> classificationMap = new HashMap<String, String>();
JsonObject linkageJson = new JsonObject();
linkageJson.addProperty("teamSet", GSON.toJson(teams, setType));
linkageJson.addProperty("classificationMap", GSON.toJson(classificationMap, mapType));
In the 2.x line of the couchbase java sdk, there is the JsonObject class that could have fit your need.
It is perfect to create Json "by hand" and still have a simple generic object representation, and is the official way of putting json into the database via the sdk.
It would go like this :
JsonObject obj = JsonObject.create();
obj.put("teamSet", JsonArray.from(new ArrayList(teams)))
.put("classificationMap", JsonObject.from(classificationMap));
Granted this is a little bit contrived because arrays and sub-objects can only be constructed from respectively List<?> and Map<String, ?> factory methods. Also the class support a limited set of value types (no custom classes, only String, Number, Boolean, etc...).
i feel somewhere it is storing it toString() representation.
Please refer below link, it might help you.
click here

How can I proccess Json faster than creating bean objects manually

For example, at the moment I am getting a list of restaurants from a Google API. then I have to create a a restaurant class with getters and setters, then I have to create objects of that class and populate them with each field from the returned json manually.
Is there another way to do this quicker than manually doing all the work?
The best thing is to find libraries for that particular API. Failing that, you could consume the JSON without mapping them to Java Beans (i.e. just parse the JSON and work with the parsed JSON by doing parsed.getString("city_name") etc.). Jackson is a good library to do that.
You could also try generating a JSON schema out of the returned JSON, then using that to auto generate Java Beans code, and then use this with a JSON library like Jackson. I tried this once but it seems that you have to fix the generated JSON schema quite a bit as the automatic schema generation tools referenced above isn't very good at the moment.
What I do is just create an object that matches the returned json string and place the values into the object using gson.fromjson()
Object.
public class Return {
private String Status;
private String[] Data;
public Return(String Status, String[] Data){
this.Status=Status;
this.Data=Data;
}
public String getStatus() { return Status; }
public String[] getData() { return Data; }
}
Code to populate Object.
java.lang.reflect.Type listType = new TypeToken<Return>(){}.getType();
Return return2= new Gson().fromJson(myresponse.toString(), listType);

Categories

Resources