Sometimes during deserialization the null is getting converted to "null". Is there a way I can avoid this?
{
"item" : {
"title": "null",
"id" : "134df"
}
}
I want it as
{
"item" : {
"title": null,
"id" : "134df"
}
}
or
{
"item" : {
"title": "",
"id": "134df"
}
}
You can achieve it by using Google JSON i.e gson.
If you are setting null against the title, then while converting the Object to JSON at that time title will not be available in the JSON string.
After that you can check a condition whether the object is available or not in the JSON and do the further task.
Here is the code spinet.
import com.google.gson.Gson;
public class JackSonObjectMapperExample {
public static void main(String[] args){
Item item = new Item();
item.setId("134df");
item.setTitle(null);
POJOExample pojo = new POJOExample();
pojo.setItem(item);
Gson gson = new Gson();
String jsonInString = gson.toJson(pojo);
System.out.println("=================>>"+jsonInString);
}
}
class POJOExample{
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
class Item{
private String title;
private String id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
output:
=================>>{"item":{"id":"134df"}}
Hope, this will help you.
Related
I am trying to automate my REST service's PUT request and I am completely new to JAva. Here I am passing a PUT body(in JSON format) along with other headers.
I had created a Java class for PUT in which I have getters and setters and I am assigning values using setter and creating my PUT body and sending this PUT body in my PUT request.
My PUT body is something like this . I am able to update "id" and "name" and create my body object but I am not sure how do I update the "versionname" and"number" under "versions" path?
{
"versions": [
{
"versionname": "Test",
"number": 1
}
],
"id": 89960004,
"name": "TEST CES LIST4",
}
The class for PUT body is as below:
public class putBody {
public String id;
public String name;
public String versionName;
public String number;
public String getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getversionName() {
return versionName;
}
public void setversionName(String versionName) {
this.versionName = versionName;
}
My question is how to update the "versionname" and "number" and create my putBody object. Any help much appreciated.
First, your PutBody class must have a collection to keep your version data, according to the JSON output that you provided.
For this purpose, just create a Version class that will be used for every single version information:
public class Version {
public String versionName;
public String number;
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
Then, here is your PutBody class should be look like
public class PutBody {
public String id;
public String name;
public List<Version> versions;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Version> getVersions() {
return versions;
}
public void setVersions(List<Version> versions) {
this.versions = versions;
}
}
And here is how to fill it with data according to your example values :
List<Version> versions = new ArrayList<Version>();
Version version = new Version();
version.setVersionName("Test");
version.setNumber("1");
versions.add(version);
PutBody putBody = new PutBody();
putBody.setName("TEST CES LIST4");
putBody.setId("89960004");
putBody.setVersions(versions);
And the JSON Output :
{
"id": "89960004",
"name": "TEST CES LIST4",
"versions": [
{
"versionName": "Test",
"number": "1"
}
]
}
UPDATE
Google's Gson has great features for this purpose. You can easily convert Java instances to JSON and convert JSON strings back to Java instances.
Please check that
My Rest service produces response as below
{
"feeds": [
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/image1.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image1.jpg"
]
},
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/mage2.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image2.jpg"
]
}
]
}
How can i parse it with Gson. IN my android client also i have same Feed Class witch which this JSON was generated.
Note: I have used Spring boot for my rest API and this JSON was generated with ResponseEntity.
Firstly, make sure that you have got valid JSON. The above in your case is not valid.
If a json object contains a single element, then there is no need to place comma after that. (comma after id in moderator and uploader object). You need to remove that.Also you need to place a comma after moderatedOn value.
Now after you got valid one, you have a feed class. In order to map your json feeds Array onto your List. You need to do the following.
Gson gson = new Gson();
Type feedsType = new TypeToken<ArrayList<Feed>>(){}.getType();
List<Feed> feedList = gson.fromJson(yourJsonResponseArray, feedsType);
Your Classes are must be like these.
Feed Class
public class Feed
{
private String id;
private String imagePath;
private Moderator moderator;
private String description;
private String rejected;
private Uploader uploader;
private String moderatedOn;
private String[] imagePaths;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getImagePath ()
{
return imagePath;
}
public void setImagePath (String imagePath)
{
this.imagePath = imagePath;
}
public Moderator getModerator ()
{
return moderator;
}
public void setModerator (Moderator moderator)
{
this.moderator = moderator;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getRejected ()
{
return rejected;
}
public void setRejected (String rejected)
{
this.rejected = rejected;
}
public Uploader getUploader ()
{
return uploader;
}
public void setUploader (Uploader uploader)
{
this.uploader = uploader;
}
public String getModeratedOn ()
{
return moderatedOn;
}
public void setModeratedOn (String moderatedOn)
{
this.moderatedOn = moderatedOn;
}
public String[] getImagePaths ()
{
return imagePaths;
}
public void setImagePaths (String[] imagePaths)
{
this.imagePaths = imagePaths;
}
}
Moderator Class
public class Moderator
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
Uploader Class
public class Uploader
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
I have in a rest response this json:
{
"TRANS": {
"HPAY": [
{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
I have made pojo class to map this json in java.
public class Trans {
private List<Hpay> hpay;
public Trans(){
}
//getter and setter
}
public class Hpay {
private String id;
private String date;
private String com;
private String msg;
private String status;
private List<Extra> extra;
private String int_msg;
private String mlabel;
private String type;
public Hpay(){
}
//getter and setter
}
I try to map the object with Gson library.
Gson gson=new Gson();
Trans transaction=gson.fromJson(response.toString(), Trans.class);
If i call hpay method on transaction i have null..i don't know why...
I have deleted previous answer and add new one as par your requirement
JSON String :
{
"TRANS": {
"HPAY": [{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
Java Objects : (Here Extra is not list)
public class MyObject {
#SerializedName("TRANS")
#Expose
private Trans trans;
public Trans getTRANS() {return trans;}
public void setTRANS(Trans trans) {this.trans = trans;}
}
public class Trans {
#SerializedName("HPAY")
#Expose
private List<HPay> hPay;
public List<HPay> getHPAY() {return hPay;}
public void setHPAY(List<HPay> hPay) {this.hPay = hPay;}
}
public class HPay {
#SerializedName("ID")
#Expose
private String id;
#SerializedName("DATE")
#Expose
private String date;
#SerializedName("REC")
#Expose
private String rec;
#SerializedName("COM")
#Expose
private String com;
#SerializedName("MSG")
#Expose
private String msg;
#SerializedName("STATUS")
#Expose
private String status;
#SerializedName("EXTRA")
#Expose
private Extra extra;
#SerializedName("INT_MSG")
#Expose
private String intMsg;
#SerializedName("MLABEL")
#Expose
private String mLabel;
#SerializedName("TYPE")
#Expose
private String type;
public String getID() {return id;}
public void setID(String id) {this.id = id;}
public String getDATE() {return date;}
public void setDATE(String date) {this.date = date;}
public String getREC() {return rec;}
public void setREC(String rec) {this.rec = rec;}
public String getCOM() {return com;}
public void setCOM(String com) {this.com = com;}
public String getMSG() {return msg;}
public void setMSG(String msg) {this.msg = msg;}
public String getSTATUS() {return status;}
public void setSTATUS(String status) {this.status = status;}
public Extra getEXTRA() {return extra;}
public void setEXTRA(Extra extra) {this.extra = extra;}
public String getINTMSG() {return intMsg;}
public void setINTMSG(String intMsg) {this.intMsg = intMsg;}
public String getMLABEL() {return mLabel;}
public void setMLABEL(String mLabel) {this.mLabel = mLabel;}
public String getTYPE() {return type;}
public void setTYPE(String type) {this.type = type;}
}
public class Extra {
#SerializedName("IS3DS")
#Expose
private String is3ds;
#SerializedName("CTRY")
#Expose
private String ctry;
#SerializedName("AUTH")
#Expose
private String auth;
public String getIS3DS() { return is3ds; }
public void setIS3DS(String is3ds) { this.is3ds = is3ds; }
public String getCTRY() { return ctry; }
public void setCTRY(String ctry) { this.ctry = ctry; }
public String getAUTH() { return auth; }
public void setAUTH(String auth) { this.auth = auth; }
}
Conversion Logic :
import com.google.gson.Gson;
public class NewClass {
public static void main(String[] args) {
Gson g = new Gson();
g.fromJson(json, MyObject.class);
}
static String json = "{ \"TRANS\": { \"HPAY\": [{ \"ID\": \"1234\", \"DATE\": \"10/09/2011 18:09:27\", \"REC\": \"wallet Ricaricato\", \"COM\": \"Tasso Commissione\", \"MSG\": \"Commento White Brand\", \"STATUS\": \"3\", \"EXTRA\": { \"IS3DS\": \"0\", \"CTRY\": \"FRA\", \"AUTH\": \"455622\" }, \"INT_MSG\": \"05-00-05 ERR_PSP_REFUSED\", \"MLABEL\": \"IBAN\", \"TYPE\": \"1\" } ] } }";
}
Here I use Google Gosn lib for conversion.
And need to import bellow classes for annotation
com.google.gson.annotations.Expose;
com.google.gson.annotations.SerializedName;
First parse the json data using json.simple and then set the values using setters
Object obj = parser.parse(new FileReader( "file.json" ));
JSONObject jsonObject = (JSONObject) obj;
JSONArray hpayObj= (JSONArray) jsonObject.get("HPAY");
//get the first element of array
JSONObject details= hpayObj.getJSONArray(0);
String id = (String)details.get("ID");
//set the value of the id field in the setter of class Trans
new Trans().setId(id);
new Trans().setDate((String)details.get("DATE"));
new Trans().setRec((String)details.get("REC"));
and so on..
//get the second array element
JSONObject intMsgObj= hpayObj.getJSONArray(1);
new Trans().setIntmsg((String)details.get("INT_MSG"));
//get the third array element
JSONObject mlabelObj= hpayObj.getJSONArray(2);
new Trans().setMlabel((String)details.get("MLABEL"));
JSONObject typeObj= hpayObj.getJSONArray(3);
new Trans().setType((String)details.get("TYPE"));
Now you can get the values using your getter methods.
I have JSON like this
{
"data":
[
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
}
]
}
]
}
I am using JSON Object to de-Serialize the data
this is what i am trying to
JSONObject jsonObj = new JSONObject(jsonStr);
String first = jsonObj.getJSONObject("data").getString("name");
System.out.println(first);
But a Cant seem to get the name or anything
Not sure what i am doing wrong?
and then i am trying to display it into a listview but haven't got to that part yet
data is a JSON Array, not a JSONObject
try: jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
also note the difference between getString and optString, if you don't want an exception on null use the later.
First parse your Json from below method,
private ArrayList<String> getStringFromJson(String jsonStr)
{
ArrayList<String> mNames = new ArrayList<String>();
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
mNames= row.getString("Name");
}
return mNames;
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
} catch (JSONException e) {
}
Data is a json array. Use getJsonObject for json objects.
Refer to this example to create a ListView and populate it's adapter with data from a json object.
Use GSON instead JSON. Hope it helps you.
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Data> datas= new ArrayList<Data>();
datas= Arrays.asList(gson.fromJson(jsonString, Data[].class));
public class Ingredients {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
public class Data {
private int id;
private String Name;
private String Image;
private String Category;
private String Method;
public List<Ingredients> getIngredients() {
return Ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
Ingredients = ingredients;
}
private List<Ingredients> Ingredients = new ArrayList<Ingredients>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
}
I am trying to convert JSON string to simple java object but it is returning null. Below are the class details.
JSON String:
{"menu":
{"id": "file",
"value": "File",
}
}
This is parsable class:
public static void main(String[] args) {
try {
Reader r = new
InputStreamReader(TestGson.class.getResourceAsStream("testdata.json"), "UTF-8");
String s = Helper.readAll(r);
Gson gson = new Gson();
Menu m = gson.fromJson(s, Menu.class);
System.out.println(m.getId());
System.out.println(m.getValue());
} catch (IOException e) {
e.printStackTrace();
}
}
Below are th model class:
public class Menu {
String id;
String value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String toString() {
return String.format("id: %s, value: %d", id, value);
}
}
Everytime i am getting null. Can anyone please help me?
Your JSON is an object with a field menu.
If you add the same in your Java it works:
class MenuWrapper {
Menu menu;
public Menu getMenu() { return menu; }
public void setMenu(Menu m) { menu = m; }
}
And an example:
public static void main(String[] args) {
String json = "{\"menu\": {\"id\": \"file\", \"value\": \"File\"} }";
Gson gson = new Gson();
MenuWrapper m = gson.fromJson(json, MenuWrapper.class);
System.out.println(m.getMenu().getId());
System.out.println(m.getMenu().getValue());
}
It will print:
file
File
And your JSON: {"menu": {"id": "file", "value": "File", } } has an error, it has an extra comma. It should be:
{"menu": {"id": "file", "value": "File" } }
What I have found helpful with Gson is to create an an instance of the class, call toJson() on it and compare the generated string with the string I am trying to parse.