I would like to create a POJO that wouldn't need to change when adding new fields to its JSON representation.
It would have some basic and required fields but will store any new fields that will be added in the future.
Examples of JSON:
{
"id": 12345,
"name":"udy",
"text": "hi, my name is udy",
"data": { "gender": "male, "age": 65, "location":{"city":"nyc"} }
}
I thought about creating this POJO:
public class Pojo{
private long id;
private String name;
private String text;
private Map data;
}
But I'm not sure this is the best option.
Couple of things in head are:
Fast serialize/deserialize to json (boon)
Flexible support for different types (lists, objects) in data field
I know that jackson can handle unknown fields, however it is pretty slow comparing to boon
Related
I'm not sure if this is at all possible as it contradicts the semantics of #XmlPath itself, but if yes, please do help me with this.
I'm getting this json by calling some external API from my API implementation
{
"title": "Forrest Gump",
"writingCredits": {
"novel": "Winston Groom",
"screenplay": "Eric Roth"
},
"directedBy": "Robert Zemeckis",
"casts": ["Tom Hanks", "Rebecca Williams", "Sally Field"],
"releaseDate": "1994-06-07T00:00:00.000Z",
"producedBy": {
"producers": ["Wendy Finerman", "Steve Starkey"],
"co-producers": ["Charles Newrith"]
}
}
and mapping this to following POJO that'll be returned as resource from my own API
public class Film
{
private String title;
#XmlPath("writingCredits/screenplay/text()")
private String writer;
#XmlPath("directedBy/text()")
private String director;
#XmlPath("casts[0]/text()")
private String actor;
#XmlJavaTypeAdapter(DateUnmarshaller.class)
#XmlPath("releaseDate/text()")
private int releaseYear;
#XmlPath("producedBy/producers[0]/text()")
private String producer;
private String category;
//Commented getters and setters to save space
}
Here I'm able to map the necessary info to my POJO using MOXy but facing problem while marshalling the same.
While marshalling it retains the original nested structure of the received json though my POJO structure is not nested, I mean it is not referring to any other POJO.
Can I get something like this when I marshall my POJO to json:
{
"title": "Forrest Gump",
"writer": "Eric Roth",
"director": "Robert Zemeckis",
"actor": "Tom Hanks",
"releaseYear": 1994,
"producer": "Wendy Finerman"
}
but instead it showed up like this:
{
"title": "Forrest Gump",
"writingCredits": {
"screenplay": "Eric Roth"
},
"directedBy": "Robert Zemeckis",
"casts": "Tom Hanks",
"releaseDate": 1994,
"producedBy": {
"producers": "Wendy Finerman"
}
}
So, is there any way to deal with this?
And one more thing, for the category attribute I wanna decide its value if a particular json entry is present in received json, e.g. if the received json contains a json entry like
"animationInfo": {
"studio" : "pixar",
"some extra info" : [],
"and some more" : {}
}
then category should be set to "animation". Do I need to write one more XmlAdapter for it?
Thank you..!
I have a json object which looks something like this
"price": {
"sale": {
"value": 39.99,
"label": "Now"
},
"regular": {
"value": 69.5,
"label": "Orig."
},
"shippingfee": 0,
"pricetype": "Markdown",
"pricetypeid": 7,
"onsale": true
}
"sale" and "regular" are keywords (unique) are 2 of the many price-types available, and the labels
"Orig" and "Now" are keywords (unique) are 2 of the many labels available.
I am not sure the best data structure to store this price json into the POJO.
can someone please guide me through this ?
I guess your problem is to convert the sale and regular attributes into an uniform representation which probably could use an Enumeration for the unique values. With default mechanism of JSON serilization/deserialization, this could be difficult. I am not sure about the JSON parsing library you are using, in Jackson there is a possibility to register custom serializers and deserializers for fields (using annotations). In this case, whcy tou would do is to register a custom serializer/deserializer and handle the fields of the JSON in the way you want it. You could refer this post
Added the below in response to the comment:
A probable dtructure for the POJO could be as below:
publi class Price{
protected List<PricePointDetails> pricePointDetails;
protected float shippingFee;
protected PriceTypes priceType;
protected priceTypeId;
protected boolean onSale;
}//class closing
public class PricePointDetails{
protected PriceTypes priceType;
protected float value;
protected LabelTypes labelType;
}//class closing
public enumeration PriceTypes{
sale,regular,markdown;
}//enumeration closing
public enumeration LabelTypes{
Orig,Now;
}//enumeration closing
What I have added, is just one way of structuring the data, it could be done in otherways also.
I am currently trying to load an indefinite amount of variables from a JSON array, and have no idea how to do this.
My JSON file is as follows:
{"commands": [
{"cmd": "hello", "params": "%u", "output": "hello %s!"},
{"cmd": "ping", "params": "", "output": "pong!"},
{"cmd": "test", "params": "%ul", "output": "test %s.."}
]}
I am using the GSON library from Google.
Would I have to manually parse each command, or is there a way to achieve this with gson.fromJson()?
You can use a wrapper object containing an array or a collection of Command objects as a model for the deserialization process:
Command.java
public class Command{
private String cmd;
private String params;
private String output;
// Getters and setters
}
CommandWrapper.java
public class CommandWrapper{
private List<Command> commands;
// Getters and setters
}
And then in your class you can deserialize the JSON this way:
Gson gson = new Gson();
CommandWrapper wrapper = gson.fromJson(myInputJson, CommandWrapper.class);
And get your commands as a list.
If the number is really indefinite; you might want to look into creating a Java8 stream from your input; as streams can be (theoretically) without an end.
But probably you should simply return a List of some specific class of yours that nicely "wraps" around the JSON data in your file.
I am having a JSON coming from response payload of rest API. below is structure of simplified JSON but the actual is much more complex.
{
"hardware": {
"cores": 2,
"cpu": 1,
},
"name": "machine11",
"network": [
{
"interface_name": "intf1",
"interface_ip": "1.1.1.1",
"interface_mac": "aa : aa: aa: aa: aa"
}
]
}
Now I have to write POJO class to bind the JSON structure using JAXB annotations (javax.xml.bind.annotation.*).
Can anyone help me how to write POJO class for a complex JSON structure,converting JSON to XML and then using XML schema to generate class is not helping out is there any other way?
Thanks in advance:-)
As per the above JSON structure, your Java objects will look like this:
public class OutermostClass{
private Hardware hardware;
private String name;
private Set<Network> network = new HashSet<Network>;
}
public class Hardware {
private int cores;
private int cpu;
}
public class Network {
private String interface_name;
private String interface_ip;
private String interface_mac
}
I am able to convert simple Json into java objects using Google Gson. The issue is I am not able to convert this specific type of response to a java object. I think this is due to the fact that I am not sure how to actually model the java classes for it. The following is the Json:
{
"List": {
"Items": [
{
"comment": "comment",
"create": "random",
"ID": 21341234,
"URL": "www.asdf.com"
},
{
"comment": "casdf2",
"create": "rafsdfom2",
"ID": 1234,
"Url": "www.asdfd.com"
}
]
},
"related": {
"Book": "ISBN",
"ID": "id"
}}
I haven't worked with Gson specifically, but I have worked with JSON / Java conversion in Jersey and JAXB.
I would say that the easiest way to translate the JSON text is to map every {..} to a Class and [..] to a List.
For example:
Class Data {
HistoryListClass HistoryList;
Relation related;
}
Class HistoryListClass {
List<History> history;
}
Class History {
String comment;
String create;
int ID;
String ttURL;
}
Class Relation {
String book;
String ID;
}
See also:
Converting JSON to Java
The "HistoryList" element in the JSON code should probably be written "historyList", and just looking at the code given, I suggest you change it to contatain the list of "History" objects directly.