Creating list of objects from a string - java

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?

Related

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

Java Constructor not working within same package

a simple one:
I am trying to use a constructor to create objects, but my objects are created empty. The constructor lives in a different class within the same package.
public static void main(String[] args) {
//Initialize all data:
ArrayList<Airport_example> all_airports = new ArrayList<Airport_example>();
Airport_example perth = new Airport_example("01","Perth","PER","Australia","WST");
Airport_example brisbane = new Airport_example("02","Brisbane","BNE","Australia","EST");
//Add airports to ArrayList
all_airports.add(perth);
all_airports.add(brisbane);
//debugging
System.out.println(all_airports);
}
The constructor in a separate class looks like this:
public class Airport_example extends HashMap<String,String> {
//list of variables
private String airportID;
private String city;
private String code3;
private String country;
private String timezone;
// constructor to initialize objects
public Airport_example(String airportID, String city, String code3, String country, String timezone) {
// Constructor variable initialization
this.airportID = airportID;
this.city = city;
this.code3 = code3;
this.country = country;
this.timezone = timezone;
}
}
The System.out.println statement returns an empty array. Have I missed a simple trick here?
[{}, {}]
Your constructor works fine; the problem is that you are extending a HashMap and expecting it to know the contents of the private fields of the Airport_example subclass. To have your print statements work as you intend them to, you have to override the toString method.
I would recommend changing your code to the following:
public class Airport_example {
private String airportID;
private String city;
private String code3;
private String country;
private String timezone;
public Airport_example(String airportID, String city, String code3, String country, String timezone) {
this.airportID = airportID;
this.city = city;
this.code3 = code3;
this.country = country;
this.timezone = timezone;
}
}
public String toString() {
// replace the string you want each object to print out
return this.airportID + ", " + this.city + ", " + this.code3 + ", " + this.country + ", " + this.timezone;
}
The reason it's printing an empty array is that it's currently calling HashMap's toString, and, as you don't define any of the HashMap fields, it's treating it as an empty HashMap.

How do i store a whole void method in array variable

public void body()
String name = "", address = "",checkin = "", checkout = "";
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
for(k =1;;k++)
{
}
I need to store whole method in a array variable at once.
well actually for every loop i want to create a element in array.
Like chrylis said in his comment you could create a class Reservation with the fields you want to store.
public class Reservation {
private String name;
private String address;
private String checkin;
private String checkout;
public Reservation(String name, String address, String checkin, String checkout) {
this.name = name;
this.address = address;
this.checkin = checkin;
this.checkout = checkout;
}
//getters and setters ...
}
Then you can create a new Object of it in your method and add it to your array
ArrayList<Reservation> reservations = new ArrayList<>();
for(k =1;;k++) {
reservations.add(new Reservation(...));
}
I used an ArrayList instead of an Array because you can add as many elements as you want to an ArrayList

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

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

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