How to save a Enum data in a POJO file to MongoDB - java

I am able to save a Simple POJO file content in MongoDB using Gson, but now I want to save the enum data inside POJO file to MongoDB. But I am not getting how to save the enum data.
This is my POJO file:
import javax.annotation.Generated;
#Generated("org.jsonschema2pojo")
public class Coverage1 {
public enum Coverage {
Hearing_Aid_Professional_Liability("HEAR"), Incidental_Motorized_Land_Conveyances_Liability_Only("LANDC"), PremisesOperations_334("PREM"), Rental_Reimbursement("RREIM"), Liquor_Law_Liability_332("LLL"), Wind("WIND"), Business_Personal_Property("BPP"), OpticianOptometrists_Professional_Liability("OOPRL"), Builders_Risk("BLDRK");
private String val;
Coverage(String val){
this.val = val;
}
public String getVal ()
{
return this.val;
}
public void setVal (String val)
{
this.val = val;
}
}
private String id;
private CoverageCd coverageCd;
private CoverageDesc coverageDesc;
private CoverageTypeCd coverageTypeCd;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public CoverageCd getCoverageCd() {
return coverageCd;
}
public void setCoverageCd(CoverageCd coverageCd) {
this.coverageCd = coverageCd;
}
public CoverageDesc getCoverageDesc() {
return coverageDesc;
}
public void setCoverageDesc(CoverageDesc coverageDesc) {
this.coverageDesc = coverageDesc;
}
public CoverageTypeCd getCoverageTypeCd() {
return coverageTypeCd;
}
public void setCoverageTypeCd(CoverageTypeCd coverageTypeCd) {
this.coverageTypeCd = coverageTypeCd;
}
}
This is my class from where I am making Mongo Call
Employee employee = new Employee(); // Create java object of Simple POJO with field No and Name
employee.setNo(2L);
employee.setName("POJO Test");
Coverage1 cv= new Coverage1();//POJO containing Enum
//How to save the Enum in Mongo
// Deserialize object to json string
Gson gson = new Gson();
String json = gson.toJson(employee);
System.out.println(json);
// Parse to bson document and insert
Document doc = Document.parse(json);
db.getCollection("NameColl").insertOne(doc);
I am now able to get the values of Enum in another class, but not getting how to save the entire data in MongoDB.
Coverage1 cv= new Coverage1();
for(Coverage1.Coverage enumval:Coverage1.Coverage.values()){
System.out.println(enumval);
cv.setValue(enumval);//How to set the entire Enum Data in Mongo
}
Please suggest how can i insert the entire Enum data in MongoDB.

You can save the constant as String calling the Enum#name() method and retrieve it back using Enum#valueOf()
Example:
myEnum.valueOf(arg0)

Related

Johnzon sub dynamic json tree mapping

In Apache Johnzon, is there a way to hava a generic field that contains dynamic JSON data, not mappable to a pre-defined POJO?
In Jackson you can simply use ObjectNode as a generic container, have some JSON processing on it, and then write the whole object in JSON format.
In Jackson it works as expected using ObjectNode, here is my code:
public class JsonTest {
private String myStaticKey = "foo";
private ObjectNode jsonData;
//code to initialize ObjectNode + getters + setters
#JsonIgnore
public void addValue(String key, String value) {
jsonData.put(key, value);
}
#JsonIgnore
public String toJson() {
return new ObjectMapper().writeValueAsString(this);
}
}
public class MainTest {
public static void main(String[] args) {
JsonTest t = new JsonTest();
t.addValue("myDynamicKey", "bar");
System.out.println(t.toJson());
}
}
Expected result:
{
"myStaticKey": "foo",
"jsonData": {
"myDynamicKey": "bar"
}
}

How to convert JSON object using GSON in Java?

Here is the JSON string return from API:
{"id":1,"bps_id":"C199","summary":{"as_of_date":"2017-06-20","bp_earned":0,"bp_balance":"199400","bp_redeemed":"600"},"bps_message":{"eng":"mobile testing message","chi":"mobile testing message chi"},"bps_image":"https:\/\/mydomain.com\/images\/eng\/promotion\/C199_MH.gif","error_message":{"eng":"","chi":""},"error_flags":""}
And I have created an object for this:
public class SummaryResponse {
String bps_id;
String bps_image;
String bps_message;
String as_of_date;
String bp_earned;
String bp_redeemed;
String bp_balance;
public String getBps_image() {
return bps_image;
}
public LangResponse getBps_message() {
return bps_message;
}
public String getAs_of_date() {
return as_of_date;
}
public String getBp_earned() {
return bp_earned;
}
public String getBp_redeemed() {
return bp_redeemed;
}
public String getBp_balance() {
return bp_balance;
}
}
It does not convert as expert, as there is some JSON object inside the string, how to convert that as well? Thanks for helping.
You can create like this,
public class SummaryResponse {
public String id;
public String bps_id;
public Summary summary;
public Message bps_message;
public String bps_image;
public Message error_message;
public String error_flags;
class Summary {
public String as_of_date;
public int bp_earned;
public String bp_balance;
public String bp_redeemed;
}
class Message {
public String eng;
public String chi;
}
}
you can call like this.
SummaryResponse summaryResponse = new Gson().fromJson([Your Json], SummaryResponse.class);
This a quick simple way to parse an array of Objects and also a single object it works for me when I am parsing json.
I believe it will only work as long as the json object is well formatted. I haven't experimented with a ill-formatted json object but that is because the api it request from was build by me, so I haven't had to worry about that
Gson gson = new Gson();
SummaryResponse[] data = gson.fromJson(jsonObj, SummaryResponse[].class);

Convert java object in JSON

I'm trying to convert a simple java object in JSON. I'm using google Gson library and it works, but I want a complete JSON object in this form:
{"Studente":[{ "nome":"John", "cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}
This is my class:
public class Studente {
private String nome;
private String cognome;
private String matricola;
private String dataNascita;
public Studente(){
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getMatricola() {
return matricola;
}
public void setMatricola(String matricola) {
this.matricola = matricola;
}
public String getDataNascita() {
return dataNascita;
}
public void setDataNascita(String dataNascita) {
this.dataNascita = dataNascita;
}
}
This is tester:
Studente x = new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson = new Gson();
String toJson = gson.toJson(x, Studente.class);
System.out.println("ToJSON "+toJson);
I have this in toJson: {"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}
The Json that you are trying to achieve is not the representation of a single Studente object, it is the representation of an object containing a list of Studente objects, that has a single entry.
So, you would need to create that extra object that contains the list of Studente objects, add the one instance to the list, and then serialize the object containing the list.
There's one minor issue, though. You are essentially asking for the wrapper object's list to have a property name that starts with a capital letter. This can be done, but breaks Java coding conventions.
It is best to write a wrapper for Students list. like this:
import java.util.ArrayList;
public class StudentWrapper {
private ArrayList<Studente> studente;
public StudentWrapper() {
studente = new ArrayList<Studente>();
}
public void addStudent(Studente s){
studente.add(s);
}
}
Code to convert to JSON :
Studente x=new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson=new Gson();
StudentWrapper studentWrapper = new StudentWrapper();
studentWrapper.addStudent(x);
String toJson=gson.toJson(studentWrapper, StudentWrapper.class);
System.out.println("ToJSON "+toJson);
The output will be like this. The way you want it.
ToJSON {"studente":[{"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}

Java JSON deserialize String with property names as field names

I am receiving from API json like that:
{
"channel":"masta",
"startTime":1427673600000,
"endTime":1427760000000,
"totalUniques":1,
"totalViewtime":1927,
"totalViews":13,
"totalCountries":1,
"countries":{
"US":{
"uniques":1,
"views":13,
"viewtime":1927
}
}
}
Now I want to deserialize it to class, so this class(Stats) will have fields like channel, startTime and so on.
But how to handle countries property?
I thought about making class Countries but not sure about that cause it's have "US" as property name. Not "country": "US". And what's more it has own parameters. How to deserialize it?
Mostly I am using ObjectMapper object.readValue(jsonString) to do that but don't know how to handle 'countries'. In example is just one country 'US' but can be more.
Declare Country class:
public class Country {
private int uniques;
private int views;
private int viewtime;
public int getUniques() {
return uniques;
}
public void setUniques(int uniques) {
this.uniques = uniques;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
public int getViewtime() {
return viewtime;
}
public void setViewtime(int viewtime) {
this.viewtime = viewtime;
}
}
In your Stats class you should declare countries as map of Country objects:
public class Stats {
private String channel;
private Long startTime;
private Long endTime;
private int totalUniques;
private int totalViewtime;
private int totalViews;
private int totalCountries;
...
private Map<String, Country> countries;
public Map<String, Country> getCountries() {
return countries;
}
public void setCountries(Map<String, Country> countries) {
this.countries = countries;
}
}
Now you can deserialize you object:
ObjectMapper mapper = new ObjectMapper();
Stats stats = mapper.readValue(jsonString, Stats.class);
After deserialization your Stack object will get map with one Country object with key "US".
Basically, you need to define a POJO like ViewInfo that has the attributes like channel, startTime, endTime and so on. countries is also another attribute, but it isn't a primitive, it's like a map with country code as the key and Country as another POJO (which has attributes like uniques, views and so on). This way, you should be able to deserialize the json into this pojo.

Retrofit returning null object

I have a JSON object that looks like this
{
id:int,
tags: [
"string",
"string"
],
images: {
waveform_l:"url_to_image",
waveform_m:"url_to_image",
spectral_m:"url_to_image",
spectral_l:"url_to_image"
}
}
I'm trying to use retrofit to parse the JSON and create the interface. The problem that I have is that I get a null for the images urls. Everything else works, I am able to retrieve the id, the tags, but when I try to get the images they are all null.
I have a sound pojo that looks like this:
public class Sound {
private Integer id;
private List<String> tags = new ArrayList<String>();
private Images images;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Images getImages() {
return images;
}
public void setImages(Images images) {
this.images = images;
}
... setters and getter for tags as well
}
and I have a Images pojo that looks like this:
public class Images {
private String waveformL;
private String waveformM;
private String spectralM;
private String spectralL;
public String getWaveformL() {
return waveformL;
}
public void setWaveformL(String waveformL) {
this.waveformL = waveformL;
}
public String getWaveformM() {
return waveformM;
}
public void setWaveformM(String waveformM) {
this.waveformM = waveformM;
}
public String getSpectralM() {
return spectralM;
}
public void setSpectralM(String spectralM) {
this.spectralM = spectralM;
}
public String getSpectralL() {
return spectralL;
}
public void setSpectralL(String spectralL) {
this.spectralL = spectralL;
}
}
Whenever I try to call images.getWaveformM() it gives me a null pointer. Any ideas?
#SerializedName can also be used to solve this. It allows you to match the expected JSON format without having to declare your Class variable exactly the same way.
public class Images {
#SerializedName("waveform_l")
private String waveformL;
#SerializedName("waveform_m")
private String waveformM;
#SerializedName("spectral_m")
private String spectralM;
#SerializedName("spectral_l")
private String spectralL;
...
}
If the only differences from the JSON to your class variables are the snake/camel case then perhaps #njzk2 answer works better but in cases where there's more differences outside those bounds then #SerializeName can be your friend.
You possibly need this part:
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) will allow gson to automatically transform the snake case into camel case.
public class Images {
private String waveform_l;
private String waveform_m;
private String spectral_m;
private String spectral_m;
}
Key name should be same in model as in json other wise it won't recognise it else you haven't define it at GsonBuilder creation.Generate the getter setter for the same and you will be good to go

Categories

Resources