Convert java object in JSON - java

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

Related

Parse JSON Data using POJO, Where key name is numeric

I'm trying to parse a special JSON data using Wrapper class, special means a JSON which have numeric keys like below :
{
"date":"2018-11-01",
"hours":"01-Nov 08:00",
"1011":"837.7500",
"1022":"99.92596979567664",
"1010":"3.198083",
"1021":"5",
"1019":"1171.000",
"1018":"3.578371",
"1017":"30.46989",
"1016":"0.0001931423",
"1015":"6749",
"1014":"0.161805",
"1013":"0.001678397",
"1012":"1.406077"
}
I know how to parse JSON data using POJO, But in this case java is not accepting the numeric as Keys.
Wrapper/POJO Class
I don't want to go with JSON object based parsing. Is Anyone have any idea about it?
The Gson library has SerializedName functionality in which it parses the corresponding value of the key defined in SerializeName's parameter. Things will be tougher if your key is a pure integer since Java disallows it as variable name, in this case SerializeName will save you from that headache and it makes your code way more maintainable.
Example usage :
#SerializedName("1011") double lat;
#SerializedName("1022") double lng;
Try Gson for create wrapper class
http://www.jsonschema2pojo.org/
public class Example {
#SerializedName("date")
#Expose
private String date;
#SerializedName("hours")
#Expose
private String hours;
#SerializedName("1011")
#Expose
private String _1011;
#SerializedName("1022")
#Expose
private String _1022;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getHours() {
return hours;
}
public void setHours(String hours) {
this.hours = hours;
}
public String get1011() {
return _1011;
}
public void set1011(String _1011) {
this._1011 = _1011;
}
public String get1022() {
return _1022;
}
public void set1022(String _1022) {
this._1022 = _1022;
}
Have a look at this code ,hope it works for you
JSONObject jsonObjectData = jsonObject1.getJSONObject("yourObject");
Iterator iterator = jsonObjectData.keys();
while (iterator.hasNext()) {
YourClass yourClass = new YourClass();
String key = (String) iterator.next();
yourClass.setKey(key);
yourClass.setVajue(jsonObjectData.getString(key));
yourList.add(yourClass);
}

Removing Strings using Regex issues

I'm trying to use the StringUtils.removeAll method to delete parts of a string and keep the other parts:
String locations = [{"code":"b","name":"Beavercreek"},{"code":"bj","name":"Beavercreek Juvenile"},...]
Here is my regex
StringUtils.removeAll(result.get("locations").toString(),"\\{\"code\":,\"name\":^[a-zA-Z0-9_.-]*$\"\"\\}");
It doesn't remove anything, I can't get the regex correct?
It looks like the string your trying to parse is JSON so I would recommend using a JSON parser. For completeness however, I'll give you a solution using a regex as well.
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) throws Exception {
String locations = "[{\"code\":\"b\",\"name\":\"Beavercreek\"},{\"code\":\"bj\",\"name\":\"Beavercreek Juvenile\"}]";
// Parsing Using a JSON Parser (Recommended)
ObjectMapper jsonMapper = new ObjectMapper();
Model[] modelArray = jsonMapper.readValue(locations, Model[].class);
for(Model model : modelArray) {
System.out.println(model.toString());
}
// Parsing Using String.replaceAll with regex
locations = locations.replaceAll("\\{\"code\":", "");
locations = locations.replaceAll("\"name\":", "");
System.out.println(locations.replaceAll("\\}", ""));
}
static class Model {
private String code;
private String name;
public Model() { }
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return String.format("%s, %s", code, name);
}
}
}
Output:
// JSON Parsing
b, Beavercreek
bj, Beavercreek Juvenile
// REGEX Parsing
["b","Beavercreek","bj","Beavercreek Juvenile"]

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);

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

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)

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