How I can add a property to a JSON was created GSON? - java

I have the following class
public class OrderShoppingCart {
#Expose
#SerializedName("id")
private String _id;
#Expose
#SerializedName("quantity")
private int _quantity;
private String _description;
private String _name;
private int _price;
#Expose
#SerializedName("selections")
private List<SelectionShoppingCart> _selections;
public OrderShoppingCart(String id, int quantity, String description, String name,int price, List<SelectionShoppingCart> selections) {
_id = id;
_quantity = Integer.valueOf(quantity);
_description = description;
_name = name;
_price = price;
_selections = selections;
}
//HERE GET AND SETTER
}
I built the GSON follows
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonG = gson.toJson(OrderShoppingCart.getOrders());
//OrderShoppingCart.getOrders() return all atributes
And I got the following
[{"id":"525b207b16b1e9ca33000143","selections":[],"quantity":1}]
but I need this
{items:[{"id":"525b207b16b1e9ca33000143","selections":[],"quantity":1}]}
How I can add what I'm missing?

Try to create a JsonObject and add a member with name items and value your Json object.
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
JsonObject jObj = new JsonObject();
jObj.add("items", gson.toJson(OrderShoppingCart.getOrders()));
String jsonG = jObj.toString();

Related

Creating list of objects from a string

I have a string:
[{location=Amsterdam-Nieuwendammerdijk, parameter=no2, date={utc=2020-02-06T18:00:00.000Z, local=2020-02-06T19:00:00+01:00}, value=-999.0, unit=µg/m³, coordinates={latitude=52.3893, longitude=4.94382}, country=NL, city=Amsterdam},
{location=Amsterdam-Einsteinweg, parameter=no2, date={utc=2020-02-06T18:00:00.000Z, local=2020-02-06T19:00:00+01:00}, value=-999.0, unit=µg/m³, coordinates={latitude=52.3813, longitude=4.84523}, country=NL, city=Amsterdam},
{location=Amsterdam-Van Diemenstraat, parameter=no2, date={utc=2020-02-06T18:00:00.000Z, local=2020-02-06T19:00:00+01:00}, value=-999.0, unit=µg/m³, coordinates={latitude=52.39, longitude=4.88781}, country=NL, city=Amsterdam}]
I need to create java objects from this string in a loop and add them to the list. Every object would be Result class object
public class Result{
private String location;
private String parameter;
private String date;
private String value;
private String unit;
private String coordinates;
private String country;
private String city;
public Result() {
}
public Result(String location, String parameter, String date, String value, String unit, String coordinates, String country, String city) {
this.location = location;
this.parameter = parameter;
this.date = date;
this.value = value;
this.unit = unit;
this.coordinates = coordinates;
this.country = country;
this.city = city;
}
I tried to create JsonArray and then iterate over this array but I got an error:
JsonArray jsonArray = (JsonArray) JsonParser.parseString(map.get("results").toString());
Caused by: com.google.gson.JsonSyntaxException:
com.google.gson.stream.MalformedJsonException: Unterminated object at
line 1 column 80 path $[0].date.utc
I've found many examples using this kind of code but when I try to uses I get an error taht says that I can't use String as a parameter.
JSONArray array = new JSONArray(jsonString);
The string I'm trying to convert to array is a value of a key from json:
String response = jsonResult(name); //jsonResult(name) - method returning json as a string
Gson gson = new Gson();
Map map = gson.fromJson(response,Map.class);
How coud I create objects out of this string?

Convert json array of arrays to some Java representation using Jackson

I am trying to convert following jsonString structure to a Java list/array of objects:
[
[1,21940000,1905386136,null,"KR","akshay","04/06/2017","03/06/2017",2017,9,40,"JPY",7478,"JPY",7478,"WHT (Residen",null,0,"03/06/2017","03/06/2017","20170604",null],
[2,21940000,1903732187,null,"KR",null,"06/06/2017","05/06/2017",2017,9,40,"JPY",608547485,"JPY",608547485,"WHT (Non-Resi",null,0,"05/06/2017","05/06/2017","20170606",null],
[3,21940000,2001898163, ............... ]
.
.
.
.
.
.
.
.
]
Below is Java code:
ObjectMapper mapper = new ObjectMapper();
MyData[][] data = mapper.readValue(jsonString, MyData[][].class);
But, I get following error:
com.fasterxml.jackson.databind.JsonMappingException:
Can not construct instance of com.org.model.MyData:
no String-argument constructor/factory method to deserialize from String value ('KR')
at [Source: java.io.StringReader#1327cf05; line: 1, column: 30] (through reference chain: java.lang.Object[][0]->java.lang.Object[][4])
Can someone help me out please? Thanks
EDIT: Below is my POJO MyData.java code:
#Entity
#Table(schema = "My_Schema", name = "My_Data_Table")
#SuppressFBWarnings(value = { "EI_EXPOSE_REP", "EI_EXPOSE_REP2" }, justification = "I prefer to suppress these FindBugs warnings")
public class MyData implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6936461726389768288L;
public MyData() {
super();
}
/**
* #param id
*/
public MyData(Long id) {
super();
this.id = id;
}
#Id
private Long id;
#Column(name = "ACCOUNT")
private long account;
#Column(name = "DOC_NUMBER")
private long docNumber;
#Column(name = "TYPE")
private String type;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "DOC_DATE")
private Date docDate;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "POSTING_DATE")
private Date postingDate;
#Column(name = "YEAR")
private long year;
#Column(name = "PERIOD")
private long period;
#Column(name = "PK")
private long pk;
#Column(name = "TAX_CODE")
private String taxCode;
#Column(name = "CCY")
private String ccy;
#Column(name = "DOC_CCY_AMT")
private long docCcyAmt;
#Column(name = "LOCAL_CCY")
private String localCcy;
#Column(name = "LOCAL_CCY_AMT")
private long localCcyAmt;
#Column(name = "TEXT")
private String text;
#Column(name = "DOC_HEADER_TEXT")
private String docHeaderText;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "CLEARING_DATE")
private Date clearingDate;
#Column(name = "CLEARING_DOC")
private long clearingDoc;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "ENTRY_DATE")
private Date entryDate;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
#Column(name = "VALUE_DATE")
private Date valueDate;
#Column(name = "ASSIGNMENT")
private String assignment;
#Column(name = "REMARKS")
private String remarks;
// Getters and setters to follow .....
So, the thing is my input JSON string is an array of arrays and I want it to be in some Java representation be it an ArrayList or plain Array...
You are probably missing required attributes for "KR" in your "MyData" class. Until you post definition for MyData class here, take a look at this code. It will surely help you.
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
and to test it
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
public class JacksonTester {
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
//map json to student
try{
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
}
catch (JsonParseException e) { e.printStackTrace();}
catch (JsonMappingException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
}

Need help to convert json to pojo

{'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111}
{'countryName':USA,'countryCode':+41,'phoneNo':4427564321,'campaignId':111}
Now I want to convert the above JSON into my POJO instances that maps to each part of the String. Suppose the POJO is called userList. Then I need to split up the JSON String to 2 userListObjects.
Your Pojo class will look like:
public class userList{
private String countryName;
private String countryCode;
private Long phoneNo;
private Integer campaignId;
//Getters,Setters
}
You can also use this_link to generate pojo just by copying and pasting your json.
Use the following snippet to generate the list.
JsonParser jsonParser = new JsonParser();
String jsonData = "[{\"countryName\":\"USA\",\"countryCode\":\"+41\",\"phoneNo\":4427564321,\"campaignId\":111},{\"countryName\":\"USA\",\"countryCode\":\"+41\",\"phoneNo\":4427564321,\"campaignId\":111}]";
JsonElement parsedJsonElement = jsonParser.parse(jsonData);
if(parsedJsonElement.isJsonArray()){
JsonArray parsedJsonArray = parsedJsonElement.getAsJsonArray();
List<User> userList = new ArrayList<User>();
for(JsonElement jsonElement : parsedJsonArray){
String countryName = "";
String countryCode = "";
long phoneNo = 0;
int campaignId = 0;
Iterator<Entry<String, JsonElement>> iterator = jsonElement.getAsJsonObject().entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, JsonElement> next = iterator.next();
String key = next.getKey();
if(key.equals("countryName")){
countryName = next.getValue().getAsString();
}else if(key.equals("countryCode")){
countryCode = next.getValue().getAsString();
}else if(key.equals("phoneNo")){
phoneNo = next.getValue().getAsLong();
}else if(key.equals("campaignId")){
phoneNo = next.getValue().getAsInt();
}
}
userList.add(new User(countryName, countryCode, phoneNo, campaignId));
}
}
public class User {
String countryName;
String countryCode;
long phoneNo;
int campaignId;
public User(String countryName, String countryCode, long phoneNo, int campaignId) {
super();
this.countryName = countryName;
this.countryCode = countryCode;
this.phoneNo = phoneNo;
this.campaignId = campaignId;
}
}

Convert JSON array to Java Class Object List

I have a JSON string that comes from a WFC service. When I try to convert JSON array into List object, I've got the following error :
".JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: java.io.StringReader#41f27f18; line: 1, column: 1]"
The Java class (Card Class):
public class Card {
public String ID;
public String CompanyID;
public String CompanyName;
public String FiscalCode;
public String Limit;
public String StateID;
public String CardState;
public String Deleted;
public String Sold;
public String StartDate;
public String InvoiceStartDate;
public String Quantity;
public String Value;
public String CardTypeID;
public String CardType;
public String SoldChanged;
public String DriverName;
public String VehiclePlateNumber;
public String VehicleID;
public String Discount;
public String ContractID;
public String DiscountPerMonth;
public String ProductID;
public String ProductStateID;
public String Mail;
public String WithoutLimit;
public String ContractSold;
public String ContractLimit;
public String NumberOfTransactions;
public String DriverNameOnly;
public String DriverSurnameOnly;
}
The Java code to deserialize :
strResponse = responseHandler.handleResponse(response);
if (strResponse.contains("Credit") || strResponse.contains("Debit")) {
ObjectMapper mapper = new ObjectMapper();
strResponse= strResponse.replace("\"GetCardsResult\":", "");
userCards = mapper.readValue(strResponse, mapper.getTypeFactory().constructCollectionType(List.class, Card.class));
}
The JSON string:
{ "GetCardsResult":"[{\"ID\":3,\"CompanyID\":1155,\"CompanyName\":\"test\",\"FiscalCode\":null,\"Code\":\"1423127205\",\"Limit\":0.000,\"StateID\":1,\"CardState\":\"Activ\",\"Deleted\":false,\"Sold\":0.000,\"StartDate\":\"\/Date(1412974800000+0300)\/\",\"InvoiceStartDate\":\"\/Date(-62135596800000+0200)\/\",\"Quantity\":null,\"Value\":0.0,\"CardTypeID\":1,\"CardType\":\"Credit\",\"SoldChanged\":false,\"DriverName\":\"\",\"VehiclePlateNumber\":\"B 222 ART\",\"VehicleID\":null,\"Discount\":null,\"ContractID\":15,\"DiscountPerMonth\":null,\"ProductID\":null,\"ProductStateID\":null,\"Mail\":\"\",\"WithoutLimit\":true,\"ContractSold\":null,\"ContractLimit\":null,\"NumberOfTransactions\":null,\"DriverNameOnly\":null,\"DriverSurnameOnly\":null},{\"ID\":2881,\"CompanyID\":1155,\"CompanyName\":\"test\",\"FiscalCode\":null,\"Code\":\"test0000\",\"Limit\":125.000,\"StateID\":1,\"CardState\":\"Activ\",\"Deleted\":false,\"Sold\":132.330,\"StartDate\":\"\/Date(1436130000000+0300)\/\",\"InvoiceStartDate\":\"\/Date(-62135596800000+0200)\/\",\"Quantity\":null,\"Value\":0.0,\"CardTypeID\":1,\"CardType\":\"Credit\",\"SoldChanged\":false,\"DriverName\":\"aaa aaa\",\"VehiclePlateNumber\":\"aaa\",\"VehicleID\":null,\"Discount\":null,\"ContractID\":15,\"DiscountPerMonth\":null,\"ProductID\":null,\"ProductStateID\":null,\"Mail\":\"\",\"WithoutLimit\":true,\"ContractSold\":null,\"ContractLimit\":null,\"NumberOfTransactions\":null,\"DriverNameOnly\":null,\"DriverSurnameOnly\":null}]" }
Thanks in advance!
Try this:
try {
JSONObject jsonObject = null;
yourJSONString.replace("\\", "");
jsonObject = new JSONObject(yourJSONString);
String newJSONString = jsonObject.get("GetCardsResult").toString();
JSONArray jsonMainArr = new JSONArray(newJSONString);
//now just loop the json Array
for (int i = 0; i < jsonMainArr.length(); ++i) {
JSONObject rec = jsonMainArr.getJSONObject(i);
card.set_id(rec.get("ID").toString());
//....
}
} catch (JSONException e) {
e.printStackTrace();
}
Try to use GSON its very efficient and easy to implement, As example below will be your POJO class.
public class Post {
#SerializedName("id")
public long ID;
public String title;
public String author;
public String url;
#SerializedName("date")
public Date dateCreated;
public String body;
public List tags;
public Post() {
}
}
//Tag.java
public class Tag {
public String name;
public String url;
public Tag() {
}
}
And this will how you parse your JSON string to Object Class,
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Post> posts = new ArrayList<Post>();
posts = Arrays.asList(gson.fromJson(reader, Post[].class));
content.close();
What do you pass to the mapper - string before or after compiling the regular expression?
Did you try any external lib like Gson? Everything you need is just new Gson().fromJson(strResponse, new TypeToken<List<Card>>() {}.getType(););

deserialize a json array using gson

I'm deserializing a json object like this:
class Offer
{
private Category category;
private String description;
private String discount;
private Date expiration;
private Date published;
private String rescinded_at;
private String title;
private Date valid_from;
private Date valid_to;
private String id;
private Business business;
private Location location;
private Long distance;
public String getDescription() {
return String.format("[Offer: description=%2$s]", description);
}
#Override
public String toString()
{
return String.format(
"[Offer: category=%1$s, description=%2$s, discount=%3$s, expiration=%4$s, published=%5$s, rescinded_at=%6$s, title=%7$s, valid_from=%8$s, valid_to=%9$s, id=%10$s, business=%11$s, location=%12$s, distance=%13$s]",
category, description, discount, expiration, published, rescinded_at, title, valid_from, valid_to, id,
business, location, distance);
}
}
As you can see, whenever there's a nested object I just refer to a class that has a toString() method for that particular nested json object. My question is: when the json object contains an array, which in my case just looks something like this:
"draws":[
"Hair Cut",
"Blow Dry",
"Blow Dry Treatment"
]
...how do I use format.toString() to deserialize this array and then put it in my Offer toString()?
Let's clarify the meaning of two terms.
Serialize: To convert an object to a sequence of bytes.
Deserialize: To parse (serialized data) so as to reconstruct the original object.
So #LuxuryMode, when you said "deserialize", did you mean "serialize"?
Assuming this is the case...
Note that your toString implementation does not currently properly generate a JSON object or array, or anything else that is valid JSON.
I recommend not using toString or any other hand-written implementation to serialize objects to JSON (or to XML or to bytes). If possible, use an API like Gson or Jackson (or XStream or the Java Serialization API).
The following example serializes a single Offer object.
// output:
// {
// "category":
// {
// "name":"category_1",
// "type":1
// },
// "description":"description_1",
// "discount":"discount_1",
// "expiration":
// {
// "value":123
// },
// "published":
// {
// "value":456
// },
// "rescinded_at":"rescinded_at_1",
// "title":"title_1",
// "valid_from":
// {
// "value":789
// },
// "valid_to":
// {
// "value":987
// },
// "id":"id_1",
// "business":
// {
// "name":"business_name_1",
// "opening_date":
// {
// "value":654
// }
// },
// "location":
// {
// "latitude":111,
// "longitude":222
// },
// "distance":333
//}
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Foo
{
public static void main(String[] args)
{
Offer offer = new Offer(
new Category("category_1", 1),
"description_1",
"discount_1",
new Date(123),
new Date(456),
"rescinded_at_1",
"title_1",
new Date(789),
new Date(987),
"id_1",
new Business("business_name_1", new Date(654)),
new Location(111, 222),
new Long(333));
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
String offerJson = gson.toJson(offer);
System.out.println(offerJson);
}
}
class Offer
{
private Category category;
private String description;
private String discount;
private Date expiration;
private Date published;
private String rescindedAt;
private String title;
private Date validFrom;
private Date validTo;
private String id;
private Business business;
private Location location;
private Long distance;
Offer(Category category,
String description,
String discount,
Date expiration,
Date published,
String rescindedAt,
String title,
Date validFrom,
Date validTo,
String id,
Business business,
Location location,
Long distance)
{
this.category = category;
this.description = description;
this.discount = discount;
this.expiration = expiration;
this.published = published;
this.rescindedAt = rescindedAt;
this.title = title;
this.validFrom = validFrom;
this.validTo = validTo;
this.id = id;
this.business = business;
this.location = location;
this.distance = distance;
}
}
class Category
{
private String name;
private int type;
Category(String name, int type)
{
this.name = name;
this.type = type;
}
}
class Date
{
private long value;
Date(long value)
{
this.value = value;
}
}
class Business
{
private String name;
private Date openingDate;
Business(String name, Date openingDate)
{
this.name = name;
this.openingDate = openingDate;
}
}
class Location
{
private int latitude;
private int longitude;
Location(int latitude, int longitude)
{
this.latitude = latitude;
this.longitude = longitude;
}
}
This next example takes the JSON output from the previous example, and deserializes it back into a Java Offer object. You can add toString and/or equals implementations to verify that all of the attributes are populated as expected, but note that the toString method is not used by Gson during deserialization or serialization.
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
String offerJson = gson.toJson(offer);
Offer offerDeserialized = gson.fromJson(offerJson, Offer.class);
To serialize an array of Offer objects is similarly simple.
Offer offer1 = new Offer(
new Category("category_1", 1),
"description_1",
"discount_1",
new Date(123),
new Date(456),
"rescinded_at_1",
"title_1",
new Date(789),
new Date(987),
"id_1",
new Business("business_name_1", new Date(654)),
new Location(111, 222),
new Long(333));
Offer offer2 = new Offer(
new Category("category_2", 2),
"description_2",
"discount_2",
new Date(234),
new Date(567),
"rescinded_at_2",
"title_2",
new Date(890),
new Date(876),
"id_2",
new Business("business_name_2", new Date(543)),
new Location(444, 555),
new Long(666));
Offer[] offers = new Offer[] {offer1, offer2};
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
String offersJson = gson.toJson(offers);
System.out.println(offersJson);
This final example takes the JSON array output from the previous example and deserializes it back into an array of Offer objects.
Offer[] offersDeserialized = gson.fromJson(offersJson, Offer[].class);

Categories

Resources