Need help to convert json to pojo - java

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

Related

Random string generator gets the same result in Java

Hello we are developing a Quiz game in Java.In our project we use Hashmap that consist of countries and their details.Each time in the loop we want to get three random countries with a random method, and we want User to answer questions related to that random country.Everytime user answers the questions related to the country we get another random country from hashmap.But we don't want these three random countries to be the same.How can we avoid that?
import java.util.HashMap;
import java.util.Random;
public class Countries {
private HashMap<String, String[]> countrieseasy;
private HashMap<String, String[]> countriesmedium;
private HashMap<String, String[]> countrieshard;
private String previousEasyCountry;
private String secondPreviousEasyCountry;
private String previousMediumCountry;
private String secondPreviousMediumCountry;
private String previousHardCountry;
private String secondPreviousHardCountry;
private Random random;
public Countries() {
countrieseasy = new HashMap<>();
countriesmedium = new HashMap<>(); // create a new HashMap object
countrieshard = new HashMap<>();
previousEasyCountry = null;
secondPreviousEasyCountry = null;
previousMediumCountry = null;
secondPreviousMediumCountry = null;
previousHardCountry = null;
secondPreviousHardCountry = null;
random = new Random();
}
public void addCountryeasy(String name, String capital, String language, String continent, String currency) {
String[] details = {name, capital, language, continent, currency};
countrieseasy.put(name, details);
}
public void addCountrymedium(String name, String capital, String language, String continent, String currency) {
String[] details = {name, capital, language, continent, currency};
countriesmedium.put(name, details);
}
public void addCountryhard(String name, String capital, String language, String continent, String currency) {
String[] details = {name, capital, language, continent, currency};
countrieshard.put(name, details);
}
public String[] getCountryeasyDetails(String name) {
return countrieseasy.get(name);
}
public String[] getCountrymediumDetails(String name) {
return countriesmedium.get(name);
}
public String[] getCountryhardDetails(String name) {
return countrieshard.get(name);
}
private String getRandomCountryName(HashMap<String, String[]> countries, String previousCountry, String secondPreviousCountry) {
Object[] countryNames = countries.keySet().toArray();
int randomIndex = random.nextInt(countryNames.length);
String countryName = (String) countryNames[randomIndex];
while (countryName.equals(previousCountry) || ( countryName.equals(secondPreviousCountry)) || (secondPreviousCountry != null && secondPreviousCountry.equals(previousCountry))) {
randomIndex = random.nextInt(countryNames.length);
countryName = (String) countryNames[randomIndex];
}
return countryName;
}
public String getRandomCountryeasyName() {
String secondPreviousCountry = previousEasyCountry;
previousEasyCountry = secondPreviousEasyCountry;
secondPreviousEasyCountry = secondPreviousCountry;
String countryName = getRandomCountryName(countrieseasy, previousEasyCountry, secondPreviousEasyCountry);
return countryName;
}
public String getRandomCountrymediumName() {
String secondPreviousCountry = previousMediumCountry;
previousMediumCountry = secondPreviousMediumCountry;
secondPreviousMediumCountry = secondPreviousCountry;
String countryName = getRandomCountryName(countriesmedium, previousEasyCountry, secondPreviousEasyCountry);
return countryName;
}
public String getRandomCountryhardName() {
String secondPreviousCountry = previousMediumCountry;
previousHardCountry = secondPreviousHardCountry;
secondPreviousHardCountry = secondPreviousCountry;
String countryName = getRandomCountryName(countriesmedium, previousEasyCountry, secondPreviousEasyCountry);
return countryName;
}
}
So here is our code we tried to give each country a string value previousName , and ckecked if it is equal to the next random country we get from hashmap but it didn't work.

How to valdiate each json array objects?

How to validate each of the names, ages and descriptions irrespective of json array index? It will kind of search that we need to validate on the basis of name, age and description with age is matching or not.
[
{
"Name": "Shobit",
"transactionDate": 1623049638000,
"age": "18",
"description": "My item for new collection addition into system with age 18"
},
{
"Name": "Neha",
"transactionDate": 1623049877000,
"age": "20",
"description": "My item for new collection addition into system with age 20"
}
]
You can convert your data to JSONArray and check each item as a JSONObject for example
JSONArray array = new JSONArray(data);
for(int i = 0; i < array.length() ; i++) {
JSONObject user = array.getJSONObject(i);
String name = user.getString("Name");
long transactionDate = user.getLong("transactionDate");
int age = user.getInt("age");
String description = user.getString("description");
// Validate here
}
Or move the validation to another method for example
JSONArray array = new JSONArray(data);
for(int i = 0; i < array.length() ; i++) {
JSONObject user = array.getJSONObject(i);
boolean isValidInfo = isValidateUser(user);
}
Validation method
public boolean isValidateUser(JSONObject user) {
String name = user.getString("Name");
long transactionDate = user.getLong("transactionDate");
int age = user.getInt("age");
String description = user.getString("description");
// Validate here
}
For java you can use the library "org.json"
Add in your pom.xml dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
Now you can use the next solution with java 8 :
JSONArray jsonArray = new JSONArray(yourJsonArray);
IntStream.range(0, jsonArray.length()).forEachOrdered(index -> {
// below the solution #AmrDeveloper
JSONObject user = jsonArray.getJSONObject(index);
String name = user.getString("Name");
long transactionDate = user.getLong("transactionDate");
int age = user.getInt("age");
String description = user.getString("description");
// Validate here
});
OR USE other libraries.
Example with Jackson
Add dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.2</version>
</dependency>
Create POJO:
public class User {
private String name;
private Long transactionDate;
private Integer age;
private String description;
public User(String name, Long transactionDate, Integer age, String description) {
this.name = name;
this.transactionDate = transactionDate;
this.age = age;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(Long transactionDate) {
this.transactionDate = transactionDate;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Create method:
public <T> Optional<List<T>> buildListObjectsFromJson(String jsonObjectsList, Class<T> clazz) {
LOGGER.info("Try to build list objects from json....");
try {
ObjectMapper objectMapper = new ObjectMapper();
List<T> objectsList = objectMapper
.readValue(jsonObjectsList, objectMapper.getTypeFactory()
.constructCollectionType(ArrayList.class, clazz));
LOGGER.info("Objects list created successfully! List size = {}", objectsList.size());
return Optional.of(objectsList);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Can't build List objects by json: {}", jsonObjectsList);
}
return Optional.empty();
}
And create use next example:
List<User> users = buildListObjectsFromJson(yourJsonArray, User.class).orElse(new ArrayList<>());
This way you can work with this data as a collection.

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?

Issue in getting the individual data parameters from the json.JsonArray

I am receiving the data from the api but the code following do not work for some reason
Here is the code:
ListeningExecutorService service = MoreExecutors.listeningDecorator(newFixedThreadPool(50));
final ListenableFuture<JsonElement> userfromapi = mClient.invokeApi("userinfo",null, "GET", null);
Futures.addCallback(userfromapi, new FutureCallback<JsonElement>() {
#Override
public void onSuccess(final JsonElement result) {
final JsonArray contacts = result.getAsJsonArray();
final String jsonString = contacts.getAsJsonObject().get("id").getAsJsonPrimitive().getAsString();
final String facebookid = contacts.getAsJsonObject().getAsJsonPrimitive("id").getAsString();
final String name = contacts.getAsJsonObject().getAsJsonArray("first_name" + "last_name").toString();
final String imgurl = "https://graph.facebook.com/" + facebookid + "/picture";
}
The problem is that, after the success call back getting the individual ids, name, etc
Make model class- For e.g
public class MyClass{
#SerializedName("Name")
private String Name;
public String getName() {
return Name;
}
}
for e.g Fetch data like this -
JSONObject jsonObject = new JSONObject(response);
MyClass myClassModel = new Gson().
fromJson(jsonObject.get("JsonArrayName").toString(),
new TypeToken<MyClass>() {
}.getType());

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

Categories

Resources