Hello so I have a model called Job. This model collects everything about a specific job. But the way the database relations are layed out means that when I return the job details I get a cargo array nested inside my job object. I want to know how I can store just the name inside the cargo array nested inside my JSON Object, I want to store it into my model.
Please may you take time to consider my situation, I have searched StackOverflow and other sites for a solution but the loops they provide aren't working. Hopefully I can find an answer by posting myself
JSON Object with nested Array:
"jobs": [
{
"id": 103080,
"user_id": 496,
"tracker_jobs_id": 91068,
"game_id": 1,
"pickup_city_id": 72,
"destination_city_id": 128,
"cargo_id": 366,
"pickup_company_id": 16,
"destination_company_id": 18,
"date": "2018-11-03",
"distance_driven": 244,
"load_damage": 7,
"estimated_income": 10956,
"total_income": 10956,
"cargo_weight": 24,
"division_load": 0,
"promotional_delivery_id": null,
"another_driver": 0,
"division_id": null,
"convoy_code": null,
"comments": null,
"created_at": "2018-11-04 00:24:42",
"updated_at": "2018-11-04 00:24:42",
"delete": "false",
"status": null,
"cargo": {
"id": 366,
"name": "Square Tubing",
"price_coef": 1,
"fragility": 0.2,
"wotr_only": 0,
"overweight_dlc": 0
},
.... (THEN IT LOOPS WITH THE NEXT JOB)
My Job Model:
public Job (int id, int user_id, int tracker_jobs_id, int game_id, int pickup_city_id, int destination_city_id,
int cargo_id, int pickup_company_id, int destination_company_id, Date date, int distance_driven, int load_damage,
int estimated_income, int total_income, int cargo_weight, int division_load, int promotional_devlivery_id, int another_driver,
int division_id, String convoy_code, String comments, String delete, String status, JSONArray cargo) {
this.id = id;
this.user_id = user_id;
this.tracker_jobs_id = tracker_jobs_id;
this.game_id = game_id;
this.pickup_city_id = pickup_city_id;
this.destination_city_id = destination_city_id;
this.cargo_id = cargo_id;
this.pickup_company_id = pickup_company_id;
this.destination_company_id = destination_company_id;
this.date = date;
this.distance_driven = distance_driven;
this.load_damage = load_damage;
this.estimated_income = estimated_income;
this.total_income = total_income;
this.cargo_weight = cargo_weight;
this.division_load = division_load;
this.promotional_devlivery_id = promotional_devlivery_id;
this.another_driver = another_driver;
this.division_id = division_id;
this.convoy_code = convoy_code;
this.comments = comments;
this.delete = delete;
this.status = status;
this.cargo = cargo;
}
As you can see I have already attempted storing it as a JSONArray but it ends up just being blank []
How I am storing it from my request:
JSONObject jObj = new JSONObject(response);
JSONArray listJobs = jObj.getJSONArray("jobs");
Gson gson = new Gson();
sUserJobs = new ArrayList<>();
for (int i = 0; i < listJobs.length(); i++) {
try {
Job job = gson.fromJson(listJobs.getJSONObject(i).toString(), Job.class);
sUserJobs.add(job);
} catch (JSONException e) {
e.printStackTrace();
}
}
You need to have a Cargo class as well. Then you need to extract cargo like below while getting Job class an set cargo object to relevant object as well.
Cargo cargo = gson.fromJson(listJobs.getJSONObject(i).getString("cargo").toString(), cargo.class);
change your Job model:
public class Job {
#SerializedName("id") // variable name from server
int id = 0;
#SerializedName("user_id")
int user_id = 0;
#SerializedName("tracker_jobs_id")
int tracker_jobs_id = 0;
#SerializedName("game_id")
int game_id = 0;
#SerializedName("pickup_city_id")
int pickup_city_id = 0;
#SerializedName("destination_city_id")
int destination_city_id = 0;
#SerializedName("cargo_id")
int cargo_id = 0;
#SerializedName("pickup_company_id")
int pickup_company_id = 0;
#SerializedName("destination_company_id")
int destination_company_id = 0;
#SerializedName("date")
String date = "";
#SerializedName("distance_driven")
int distance_driven = 0;
#SerializedName("load_damage")
int load_damage = 0;
#SerializedName("estimated_income")
int estimated_income = 0;
#SerializedName("total_income")
int total_income = 0;
#SerializedName("cargo_weight")
int cargo_weight = 0;
#SerializedName("division_load")
int division_load = 0;
#SerializedName("promotional_devlivery_id")
int promotional_devlivery_id = 0;
#SerializedName("another_driver")
int another_driver = 0;
#SerializedName("division_id")
int division_id = 0;
#SerializedName("convoy_code")
String convoy_code = "";
#SerializedName("comments")
String comments = "";
#SerializedName("delete")
String delete = "";
#SerializedName("status")
String status = "";
#SerializedName("cargo")
Cargo cargo = new Cargo();
public Job (int id, int user_id, int tracker_jobs_id, int game_id, int pickup_city_id, int destination_city_id,
int cargo_id, int pickup_company_id, int destination_company_id, String date, int distance_driven, int load_damage,
int estimated_income, int total_income, int cargo_weight, int division_load, int promotional_devlivery_id, int another_driver,
int division_id, String convoy_code, String comments, String delete, String status, Cargo cargo) {
this.id = id;
this.user_id = user_id;
this.tracker_jobs_id = tracker_jobs_id;
this.game_id = game_id;
this.pickup_city_id = pickup_city_id;
this.destination_city_id = destination_city_id;
this.cargo_id = cargo_id;
this.pickup_company_id = pickup_company_id;
this.destination_company_id = destination_company_id;
this.date = date;
this.distance_driven = distance_driven;
this.load_damage = load_damage;
this.estimated_income = estimated_income;
this.total_income = total_income;
this.cargo_weight = cargo_weight;
this.division_load = division_load;
this.promotional_devlivery_id = promotional_devlivery_id;
this.another_driver = another_driver;
this.division_id = division_id;
this.convoy_code = convoy_code;
this.comments = comments;
this.delete = delete;
this.status = status;
this.cargo = cargo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getTracker_jobs_id() {
return tracker_jobs_id;
}
public void setTracker_jobs_id(int tracker_jobs_id) {
this.tracker_jobs_id = tracker_jobs_id;
}
public int getGame_id() {
return game_id;
}
public void setGame_id(int game_id) {
this.game_id = game_id;
}
public int getPickup_city_id() {
return pickup_city_id;
}
public void setPickup_city_id(int pickup_city_id) {
this.pickup_city_id = pickup_city_id;
}
public int getDestination_city_id() {
return destination_city_id;
}
public void setDestination_city_id(int destination_city_id) {
this.destination_city_id = destination_city_id;
}
public int getCargo_id() {
return cargo_id;
}
public void setCargo_id(int cargo_id) {
this.cargo_id = cargo_id;
}
public int getPickup_company_id() {
return pickup_company_id;
}
public void setPickup_company_id(int pickup_company_id) {
this.pickup_company_id = pickup_company_id;
}
public int getDestination_company_id() {
return destination_company_id;
}
public void setDestination_company_id(int destination_company_id) {
this.destination_company_id = destination_company_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getDistance_driven() {
return distance_driven;
}
public void setDistance_driven(int distance_driven) {
this.distance_driven = distance_driven;
}
public int getLoad_damage() {
return load_damage;
}
public void setLoad_damage(int load_damage) {
this.load_damage = load_damage;
}
public int getEstimated_income() {
return estimated_income;
}
public void setEstimated_income(int estimated_income) {
this.estimated_income = estimated_income;
}
public int getTotal_income() {
return total_income;
}
public void setTotal_income(int total_income) {
this.total_income = total_income;
}
public int getCargo_weight() {
return cargo_weight;
}
public void setCargo_weight(int cargo_weight) {
this.cargo_weight = cargo_weight;
}
public int getDivision_load() {
return division_load;
}
public void setDivision_load(int division_load) {
this.division_load = division_load;
}
public int getPromotional_devlivery_id() {
return promotional_devlivery_id;
}
public void setPromotional_devlivery_id(int promotional_devlivery_id) {
this.promotional_devlivery_id = promotional_devlivery_id;
}
public int getAnother_driver() {
return another_driver;
}
public void setAnother_driver(int another_driver) {
this.another_driver = another_driver;
}
public int getDivision_id() {
return division_id;
}
public void setDivision_id(int division_id) {
this.division_id = division_id;
}
public String getConvoy_code() {
return convoy_code;
}
public void setConvoy_code(String convoy_code) {
this.convoy_code = convoy_code;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getDelete() {
return delete;
}
public void setDelete(String delete) {
this.delete = delete;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<Cargo> getCargo() {
return cargo;
}
public void setCargo(List<Cargo> cargo) {
this.cargo = cargo;
}
}
and Create New Class named: Cargo
public class Cargo {
#SerializedName("id")
int id = 0;
#SerializedName("name")
String name = "";
#SerializedName("price_coef")
int price_coef = 0;
#SerializedName("fragility")
double fragility = 0.0;
#SerializedName("wotr_only")
int wotr_only = 0;
#SerializedName("overweight_dlc")
int overweight_dlc = 0;
public Cargo () {
}
public Cargo (int id, String name, int price_coef, double fragility, int wotr_only, int overweight_dlc) {
this.id = id;
this.name = name;
this.price_coef = price_coef;
this.fragility = fragility;
this.wotr_only = wotr_only;
this.overweight_dlc = overweight_dlc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice_coef() {
return price_coef;
}
public void setPrice_coef(int price_coef) {
this.price_coef = price_coef;
}
public double getFragility() {
return fragility;
}
public void setFragility(double fragility) {
this.fragility = fragility;
}
public int getWotr_only() {
return wotr_only;
}
public void setWotr_only(int wotr_only) {
this.wotr_only = wotr_only;
}
public int getOverweight_dlc() {
return overweight_dlc;
}
public void setOverweight_dlc(int overweight_dlc) {
this.overweight_dlc = overweight_dlc;
}
}
or.. you can post your json to this site and download your models:
http://www.jsonschema2pojo.org/
Target language: Java
Source type: JSON Schema or JSON
Annotation style: Gson
Related
I'm trying to get the data from the arrayBundlePack after getting data from enqueue call, I'm trying to use BufferedWriter to the saved data in the arrayBundlePack & write in the txt file, but it just won't get the output I wanted.
I'm not sure if that's the way to output an arrayList model class.
Here's the code
private ArrayList<BundlePack> arrayBundlePack;
Call<BundlePackRepo> call = .............. // api content
call.enqueue(new Callback<BundlePackRepo>() {
#Override
public void onResponse(Call<BundlePackRepo> call, retrofit2.Response<BundlePackRepo> response) {
if (response.isSuccessful()) {
BundlePackRepo repos = response.body();
BundlePackRepo.bundlepacks[] bundlePacksarray;
bundlePacksarray = repos.getBundlePacks();
BundlePack bundlePack;
for (int a = 0; a < bundlePacksarray.length; a++) {
bundlePack = new BundlePack();
bundlePack.setPromotion_kit(bundlePacksarray[a].getPromotion_kit());
bundlePack.setStock_code(bundlePacksarray[a].getStock_code());
bundlePack.setIssue_ref(bundlePacksarray[a].getIssue_ref());
bundlePack.setQuantity(bundlePacksarray[a].getQuantity());
String sysMod = bundlePacksarray[a].getSys_mod();
String modifyDate = bundlePacksarray[a].getModify_dt();
try {
bundlePack.setSys_mod(df.parse(sysMod));
bundlePack.setModify_dt(df.parse(modifyDate));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
bundlePack.setStatus(bundlePacksarray[a].getStatus());
arrayBundlePack.add(bundlePack);
//Trying to put out the data to text file
String filename = "bundlepack.txt";
File txtData = new File(getApplicationContext().getFilesDir(), filename);
FileWriter txtWriter = null;
try {
txtWriter = new FileWriter(txtData);
BufferedWriter fileWriter = new BufferedWriter(txtWriter);
for (BundlePack bdpack : arrayBundlePack) {
fileWriter.write(bdpack.toString());
fileWriter.newLine();
fileWriter.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
BundlePack
#Entity
public class BundlePack{
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "promotion_kit")
private String promotion_kit;
#ColumnInfo(name = "stock_code")
private String stock_code;
#ColumnInfo(name = "issue_ref")
private String issue_ref;
#ColumnInfo(name = "quantity")
private Integer quantity;
#TypeConverters(DateConverter.class)
#ColumnInfo(name = "sys_mod")
private Date sys_mod;
#TypeConverters(DateConverter.class)
#ColumnInfo(name = "modify_dt")
private Date modify_dt;
#ColumnInfo(name = "status")
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPromotion_kit() {
return promotion_kit;
}
public void setPromotion_kit(String promotion_kit) {
this.promotion_kit = promotion_kit;
}
public String getStock_code() {
return stock_code;
}
public void setStock_code(String stock_code) {
this.stock_code = stock_code;
}
public String getIssue_ref() {
return issue_ref;
}
public void setIssue_ref(String issue_ref) {
this.issue_ref = issue_ref;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Date getSys_mod() {
return sys_mod;
}
public void setSys_mod(Date sys_mod) {
this.sys_mod = sys_mod;
}
public Date getModify_dt() {
return modify_dt;
}
public void setModify_dt(Date modify_dt) {
this.modify_dt = modify_dt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "BundlePack{" +
"id=" + id +
", promotion_kit='" + promotion_kit + '\'' +
", stock_code='" + stock_code + '\'' +
", issue_ref='" + issue_ref + '\'' +
", quantity=" + quantity +
", sys_mod=" + sys_mod +
", modify_dt=" + modify_dt +
", status='" + status + '\'' +
'}';
}
}
BundlePackRepo
public class BundlePackRepo {
private String count;
private bundlepacks[] bundlepacks;
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public bundlepacks[] getBundlePacks() {
return bundlepacks;
}
public void setBundlePacks(bundlepacks[] bundlePacks) {
this.bundlepacks = bundlePacks;
}
public static class bundlepacks {
#SerializedName("promotionkit")
private String promotion_kit;
#SerializedName("stock_code")
private String stock_code;
#SerializedName("iss_ref")
private String issue_ref;
#SerializedName("qty")
private int quantity;
#SerializedName("sys_mod")
private String sys_mod;
#SerializedName("modify_dt")
private String modify_dt;
#SerializedName("status")
private String status;
#SerializedName("id")
private String id;
public String getPromotion_kit() {
return promotion_kit;
}
public void setPromotion_kit(String promotion_kit) {
this.promotion_kit = promotion_kit;
}
public String getStock_code() {
return stock_code;
}
public void setStock_code(String stock_code) {
this.stock_code = stock_code;
}
public String getIssue_ref() {
return issue_ref;
}
public void setIssue_ref(String issue_ref) {
this.issue_ref = issue_ref;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getSys_mod() {
return sys_mod;
}
public void setSys_mod(String sys_mod) {
this.sys_mod = sys_mod;
}
public String getModify_dt() {
return modify_dt;
}
public void setModify_dt(String modify_dt) {
this.modify_dt = modify_dt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
}
You are calling toString() to convert each bundlepack instance to a string for output. So you need to an override for toString to the bundlepack class. It needs to format the instance in the form that you need for your purposes.
Since you currently haven't overridden that method, your code is currently calling Object.toString() ... which only outputs the object's class name and hashcode.
Your IDE may well have a helper to generate a toString for a class, based on the fields of the class.
I'm trying to deal with this baking JSON:
in android app so this is the class to bring the JSON data from link:
OpenBakingJsonUtils.java:
public final class OpenBakingJsonUtils {
public static ArrayList<ArraysLists> getSimpleBakingStringsFromJson(Context context, String bakingJsonString)
throws JSONException {
final String ID = "id";
final String NAME = "name";
final String SERVINGS = "servings";
final String INGREDIENTS = "ingredients";
final String STEPS = "steps";
final String QUANTITY = "quantity";
final String MEASURE = "measure";
final String INGREDIENT = "ingredient";
final String IDSTEPS = "id";
final String SHORTDESCRIPTION = "shortDescription";
final String DESCRIPTION = "description";
final String VIDEOURL = "videoURL";
final String THUMBNAILURL = "thumbnailURL";
ArrayList<ArraysLists> parsedRecipeData = new ArrayList<ArraysLists>();
ArrayList<BakingItem> Baking = new ArrayList<BakingItem>();
JSONArray recipeArray = new JSONArray(bakingJsonString);
for (int i = 0; i < recipeArray.length(); i++) {
int id;
String name;
int servings;
double quantity;
String measure;
String ingredient;
int idSteps;
String shortDescription;
String description;
String videoURL;
String thumbnailURL;
JSONObject recipeObject = recipeArray.getJSONObject(i);
id = recipeObject.getInt(ID);
name = recipeObject.getString(NAME);
servings = recipeObject.getInt(SERVINGS);
ArrayList<IngredientsItem> Ingredients = new ArrayList<IngredientsItem>();
JSONArray ingredientsArray = recipeObject.getJSONArray(INGREDIENTS);
for(int j = 0 ; j< ingredientsArray.length(); j++) {
JSONObject ingredientsObject = ingredientsArray.getJSONObject(j);
quantity = ingredientsObject.getDouble(QUANTITY);
measure = ingredientsObject.getString(MEASURE);
ingredient = ingredientsObject.getString(INGREDIENT);
Ingredients.add(new IngredientsItem(quantity, measure, ingredient));
}
ArrayList<StepsItem> Steps = new ArrayList<StepsItem>();
JSONArray stepsArray = recipeObject.getJSONArray(STEPS);
for(int j = 0 ; j< stepsArray.length(); j++) {
JSONObject stepsObject = stepsArray.getJSONObject(j);
idSteps = recipeObject.getInt(IDSTEPS);
shortDescription = stepsObject.getString(SHORTDESCRIPTION);
description = stepsObject.getString(DESCRIPTION);
videoURL = stepsObject.getString(VIDEOURL);
thumbnailURL = stepsObject.getString(THUMBNAILURL);
Steps.add(new StepsItem(idSteps, shortDescription, description, videoURL, thumbnailURL));
}
Baking.add(new BakingItem(id, name, servings, Ingredients, Steps));
parsedRecipeData.add(new ArraysLists(Baking, Ingredients, Steps));
}
return parsedRecipeData;
}
}
as you see there are 3 ArrayList classes:
ArrayList<BakingItem>
ArrayList<IngredientsItem>
ArrayList<StepsItem>
and this is the code for each one:
BakingItem.java:
public class BakingItem implements Parcelable {
private int id;
private String name;
private int servings;
private ArrayList<IngredientsItem> ingredients = new ArrayList<IngredientsItem>();
private ArrayList<StepsItem> steps = new ArrayList<StepsItem>();
public BakingItem(int id, String name, int servings, ArrayList<IngredientsItem> ingredients, ArrayList<StepsItem> steps) {
this.id = id;
this.name = name;
this.servings = servings;
this.ingredients = ingredients;
this.steps = steps;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(name);
out.writeInt(servings);
out.writeTypedList(ingredients);
out.writeTypedList(steps);
}
private BakingItem(Parcel in) {
this.id = in.readInt();
this.name = in.readString();
this.servings = in.readInt();
ingredients = new ArrayList<IngredientsItem>();
in.readTypedList(ingredients, IngredientsItem.CREATOR);
}
public BakingItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<BakingItem> CREATOR = new Parcelable.Creator<BakingItem>() {
#Override
public BakingItem createFromParcel(Parcel in) {
return new BakingItem(in);
}
#Override
public BakingItem[] newArray(int i) {
return new BakingItem[i];
}
};
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getServings() {
return servings;
}
}
IngredientsItem.java:
public class IngredientsItem implements Parcelable {
private double quantity;
private String measure;
private String ingredient;
public IngredientsItem(double quantity, String measure, String ingredient) {
this.quantity = quantity;
this.measure = measure;
this.ingredient = ingredient;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeDouble(quantity);
out.writeString(measure);
out.writeString(ingredient);
}
private IngredientsItem(Parcel in) {
this.quantity = in.readDouble();
this.measure = in.readString();
this.ingredient = in.readString();
}
public IngredientsItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<IngredientsItem> CREATOR = new Parcelable.Creator<IngredientsItem>() {
#Override
public IngredientsItem createFromParcel(Parcel in) {
return new IngredientsItem(in);
}
#Override
public IngredientsItem[] newArray(int i) {
return new IngredientsItem[i];
}
};
public double getQuantity() {
return quantity;
}
public String getMeasure() {
return measure;
}
public String getIngredient() {
return ingredient;
}
}
as well as the StepsItem class
and the forth is the ArraysLists.java which contain all the 3 arrays above and returned by the OpenBakingJsonUtils.java:
Then I'm trying to call these JSON data in different activities
so in MainActivity.java in loadInBackground:
Override
public ArrayList<BakingItem> loadInBackground() {
URL recipeRequestUrl = NetworkUtils.buildUrl();
try {
String jsonBakingResponse = NetworkUtils.getResponseFromHttpUrl(recipeRequestUrl);
ArrayList<ArraysLists> simpleJsonBakingData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(MainActivity.this, jsonBakingResponse);
return simpleJsonBakingData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I call the returned ArrayList from OpenBakingJsonUtils.java which is in this case the ArraysLists,
then in DetailActivity.java in doInBackground:
#Override
protected ArrayList<ArraysLists> doInBackground(Object... params) {
if (params.length == 0) {
return null;
}
URL reviewsRequestUrl = NetworkUtils.buildUrl();
try {
String jsonReviewResponse = NetworkUtils.getResponseFromHttpUrl(reviewsRequestUrl);
ArrayList<ArraysLists> simpleJsonReviewData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(DetailsActivity.this, jsonReviewResponse);
return simpleJsonReviewData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
here I call the ArrayList of ArraysLists too but the problem in adapters of MainActivity.java and DetailsActivity.java in onBindViewHolder:
holder.CommentContent.setText(String.valueOf(mCommentsItems.get(position).getQuantity()));
it just says that cannot resolve method getQuantity() which is in IngredientsItem.java while I used the ArraysLists.java that returned by OpenBakingJsonUtils.java
so what should I do to call methods from BakingItem.java and IngredientsItem.java while I use the returned ArraysLists.java ?
The problem I'm having is with the superclass. I can't change the new Property(...) to another class called House. The only difference is the information in them, but once I change it I am getting an error stating that the constructor doesn't match but I thought that the super() should pass the information on.
This is how my Array is set up:
public static void main(String[] args) {
Property [] Properties = new Property[25];
Properties[0] = new Property (1001, 200, "58 Lackagh Park", "Dungiven", "BT47 4ND", new MyDate(15,05,2018), 5000.00, 800.50, 40.50);
Properties[1] = new Property (1002, 500, "24 Jop Lane", "Kelflar", "VT57 5LP", new MyDate(10,06,2018), 12000.00, 1000.00, 60.00);
Properties[2] = new Property (1003, 100, "Lot B", "Bandlebop", "LU49 3JU", new MyDate(01,07,2018), 450.00, 800.00, 50.50);
Properties[3] = new Property (1004, 200, "12 Back Lane", "Galafray", "GA1 1Fy", new MyDate(05,12,2018), 50000.00, 1000.00, 80.00);
Properties[4] = new Property (1005, 200, "43 Pop Street", "Jundar", "BY78 1JH", new MyDate(11,12,2018), 2500.00, 600.50, 32.90);
Properties[5] = new Property (1006, 200, "123 Fake Street", "Dunlem", "BL09 4PL", new MyDate(21,03,2018), 65000.00, 700.50, 56.50);
Properties[6] = new Property (1007, 200, "09012 Bakers Field", "Bristol", "LO87 D0N", new MyDate(15,05,2018), 5000.00, 200.50, 40.50);
Properties[7] = new Property (1008, 200, "Unit B high Street", "LA", "LA58 7NL", new MyDate(18,11,2018), 20000.00, 1000.00, 90.00);
Properties[8] = new Property (1009, 200, "1 Flabbergast Park", "Nubb", "HJ98 7NH", new MyDate(10,03,2018), 4958.00, 900.20, 20.50);
Properties[9] = new Property (1010, 200, "29 Bakers Field", "London Town", "HU84 2JO", new MyDate(02,05,2018), 1234.00, 800.00, 40.50);
Properties[10] = new Property (1011, 200, "20 Peliper Lane", "Dungiven", "BT47 4FE", new MyDate(15,05,2018), 4321.00, 900.00, 20.00);
Here is the Property class:
public class Property {
private int PropertyNumber, SquareFoot;
private String Address,Town,PostCode;
private MyDate DateListed;
public double Price;
private double Rates;
private double PricePerSquareFoot;
public Property() {
PropertyNumber = 0;
SquareFoot = 0;
Address = "";
Town = "";
PostCode = "";
DateListed = new MyDate();
Price = 0.0;
Rates = 0.0;
PricePerSquareFoot = 0.0;
}
public Property(int PropertyNumber, int SquareFoot, String Address, String Town, String PostCode, MyDate DateListed, double Price, double rates, double PricePerSquareFoot)
{
super();
this.PropertyNumber = PropertyNumber;
this.SquareFoot = SquareFoot;
this.Address = Address;
this.Town = Town;
this.PostCode = PostCode;
this.DateListed = DateListed;
this.Price = Price;
this.Rates = Rates;
this.PricePerSquareFoot = PricePerSquareFoot;
}
//--------Getters and setters----------------//
public void setPropertyNumber(int PropertyNumber)
{
this.PropertyNumber = PropertyNumber;
}
public int getPropertyNumber()
{
return PropertyNumber;
}
public void setSquareFoot(int SquareFoot)
{
this.SquareFoot = SquareFoot;
}
public int getSquareFoot()
{
return SquareFoot;
}
public void setAddress(String Address)
{
this.Address = Address;
}
public String getAddress()
{
return Address;
}
public void setTown( String Town)
{
this.Town = Town;
}
public String getTown()
{
return Town;
}
public void setPostcode( String PostCode)
{
this.PostCode = PostCode;
}
public String GetPostcode()
{
return PostCode;
}
public void setDateListed(MyDate DateListed)
{
this.DateListed = DateListed;
}
public MyDate getDateListed()
{
return DateListed;
}
public void setPrice(double Price)
{
this.Price = Price;
}
public double getPrice()
{
return Price;
}
public void setRates(double Rates)
{
this.Rates = Rates;
}
public double getRates()
{
return Rates;
}
public void setPricePerSquareFoot(double PricePerSqaureFoot)
{
this.PricePerSquareFoot = PricePerSquareFoot;
}
public double getPricePerSquareFoot()
{
return PricePerSquareFoot;
}
And this is what I am trying to put into the array along with the property information such as Property number price etc:
public class House extends Residential {
private int Garden;
private int Garage;
public House() {
super();
Garage = 0;
Garden = 0;
}
public House(int Garage, int garden) {
super();
this.Garage = 0;
this.Garden = 0;
}
public void setGarage(int Garage)
{
this.Garage = Garage;
}
public int getGarage()
{
return Garage;
}
public void setGarden(int Garden)
{
this.Garden = Garden;
}
public int getGarden()
{
return Garden;
}
.......
This is the residential class
public class Residential extends Property
{
private int NumberOfBedrooms;
private int NumberOfBathrooms;
public Residential()
{
super();
NumberOfBedrooms = 0;
NumberOfBathrooms = 0;
}
public void setNumberOfBedrooms(int NumberOfBedrooms)
{
this.NumberOfBedrooms = NumberOfBedrooms;
}
public int getNumberOfBedrooms()
{
return NumberOfBedrooms;
}
public void setNumberOfBathrooms(int NumberOfBathrooms)
{
this.NumberOfBathrooms = NumberOfBathrooms;
}
public int getNumberOfBathrooms()
{
return NumberOfBathrooms;
}
public Residential(int NumberOfBedrooms, int NumberOfBathrooms)
{
super();
NumberOfBedrooms = 0;
NumberOfBathrooms = 0;
}
Previously I was reading json data in the following format:
JSON
{
"CreationTime":"2018-01-12T12:32:31",
"Id":"08f81fd7-21f1-48ba-a991-08d559b88cc5",
"Operation":"AddedToGroup",
"RecordType":14,
"UserType":0,
"Version":1,
"Workload":"OneDrive",
"ClientIP":"115.186.129.229",
"UserId":"omaji7#emumbaa10.onmicrosoft.com",
"EventSource":"SharePoint",
"ItemType":"Web"
}
I am reading this json data from a kafka topic and doing some stream processing on it and passing it onto another topic. In processing I have created two json objects, send and received.
Using this code:
final StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> source_o365_user_activity = builder.stream("o365_user_activity");
source_o365_user_activity.flatMapValues(new ValueMapper<String, Iterable<String>>() {
#Override
public Iterable<String> apply(String value) {
System.out.println("========> o365_user_activity_by_date Log: " + value);
ArrayList<String> keywords = new ArrayList<String>();
try {
JSONObject send = new JSONObject();
JSONObject received = new JSONObject(value);
send.put("current_date", getCurrentDate().toString()); // UTC TIME
send.put("activity_time", received.get("CreationTime")); // CONSTANTS FINAL STATIC(Topic Names, Cassandra keys)
send.put("user_id", received.get("UserId"));
send.put("operation_type", received.get("Operation"));
send.put("app_name", received.get("Workload"));
keywords.add(send.toString());
// apply regex to value and for each match add it to keywords
} catch (Exception e) {
// TODO: handle exception
System.err.println("Unable to convert to json");
e.printStackTrace();
}
return keywords;
}
}).to("o365_user_activity_by_date");
This was fairly simple. Now I have a json data with lists in them.
JSON
{
"CreationTime":"2017-12-27T07:47:46",
"Id":"10ee505b-90a4-4ac1-b96f-a6dbca939694",
"Operation":"Add member to role.",
"OrganizationId":"2f88f444-62da-4aae-b8af-8331a6915801",
"RecordType":8,
"ResultStatus":"success",
"UserKey":"10030000A656FE5B#emumbaa10.onmicrosoft.com",
"UserType":0,
"Version":1,
"Workload":"AzureActiveDirectory",
"ObjectId":"mustafa#emumbaa10.onmicrosoft.com",
"UserId":"omaji7#emumbaa10.onmicrosoft.com",
"AzureActiveDirectoryEventType":1,
"ExtendedProperties":[
{
"Name":"Role.ObjectID",
"Value":"b0f54661-2d74-4c50-afa3-1ec803f12efe"
},
{
"Name":"Role.DisplayName",
"Value":"Billing Administrator"
},
{
"Name":"Role.TemplateId",
"Value":"b0f54661-2d74-4c50-afa3-1ec803f12efe"
},
{
"Name":"Role.WellKnownObjectName",
"Value":"BillingAdmins"
}
],
"Actor":[
{
"ID":"omaji7#emumbaa10.onmicrosoft.com",
"Type":5
},
{
"ID":"10030000A656FE5B",
"Type":3
},
{
"ID":"User_d03ca514-adfa-4585-a8bd-7182a9a086c7",
"Type":2
}
],
"ActorContextId":"2f88f444-62da-4aae-b8af-8331a6915801",
"InterSystemsId":"6d402a5b-c5de-4d9f-a805-9371c109e55f",
"IntraSystemId":"a5568d01-f100-497a-b88b-c9731ff31248",
"Target":[
{
"ID":"User_8f77c311-3ea0-4146-9f7d-db21bd052d3d",
"Type":2
},
{
"ID":"mustafa#emumbaa10.onmicrosoft.com",
"Type":5
},
{
"ID":"1003BFFDA67CCA03",
"Type":3
}
],
"TargetContextId":"2f88f444-62da-4aae-b8af-8331a6915801"
}
How can I go about doing the same thing in my Stream processing?
I want to be able to read JSON data against some keys (including the list data keys).
Why not convert JSON to Object and then filter against using the field in Object?
Can't you do like this?
send.put("target_0_id", received.get("Target").getJSONObject(0).get("ID"));
You can use gson library and can convert the json to object and using getter and setter you can build your desired output JSON. You can also parse the input JSON to fetch the JSONArray details. Following is the code how you can do it using POJO.
Input class:
public class Input {
private String UserType;
private String TargetContextId;
private String RecordType;
private String Operation;
private String Workload;
private String UserId;
private String OrganizationId;
private String InterSystemsId;
private ExtendedProperties[] ExtendedProperties;
private String ActorContextId;
private String CreationTime;
private String IntraSystemId;
private Target[] Target;
private Actor[] Actor;
private String Id;
private String Version;
private String ResultStatus;
private String ObjectId;
private String AzureActiveDirectoryEventType;
private String UserKey;
public String getUserType ()
{
return UserType;
}
public void setUserType (String UserType)
{
this.UserType = UserType;
}
public String getTargetContextId ()
{
return TargetContextId;
}
public void setTargetContextId (String TargetContextId)
{
this.TargetContextId = TargetContextId;
}
public String getRecordType ()
{
return RecordType;
}
public void setRecordType (String RecordType)
{
this.RecordType = RecordType;
}
public String getOperation ()
{
return Operation;
}
public void setOperation (String Operation)
{
this.Operation = Operation;
}
public String getWorkload ()
{
return Workload;
}
public void setWorkload (String Workload)
{
this.Workload = Workload;
}
public String getUserId ()
{
return UserId;
}
public void setUserId (String UserId)
{
this.UserId = UserId;
}
public String getOrganizationId ()
{
return OrganizationId;
}
public void setOrganizationId (String OrganizationId)
{
this.OrganizationId = OrganizationId;
}
public String getInterSystemsId ()
{
return InterSystemsId;
}
public void setInterSystemsId (String InterSystemsId)
{
this.InterSystemsId = InterSystemsId;
}
public ExtendedProperties[] getExtendedProperties ()
{
return ExtendedProperties;
}
public void setExtendedProperties (ExtendedProperties[] ExtendedProperties)
{
this.ExtendedProperties = ExtendedProperties;
}
public String getActorContextId ()
{
return ActorContextId;
}
public void setActorContextId (String ActorContextId)
{
this.ActorContextId = ActorContextId;
}
public String getCreationTime ()
{
return CreationTime;
}
public void setCreationTime (String CreationTime)
{
this.CreationTime = CreationTime;
}
public String getIntraSystemId ()
{
return IntraSystemId;
}
public void setIntraSystemId (String IntraSystemId)
{
this.IntraSystemId = IntraSystemId;
}
public Target[] getTarget ()
{
return Target;
}
public void setTarget (Target[] Target)
{
this.Target = Target;
}
public Actor[] getActor ()
{
return Actor;
}
public void setActor (Actor[] Actor)
{
this.Actor = Actor;
}
public String getId ()
{
return Id;
}
public void setId (String Id)
{
this.Id = Id;
}
public String getVersion ()
{
return Version;
}
public void setVersion (String Version)
{
this.Version = Version;
}
public String getResultStatus ()
{
return ResultStatus;
}
public void setResultStatus (String ResultStatus)
{
this.ResultStatus = ResultStatus;
}
public String getObjectId ()
{
return ObjectId;
}
public void setObjectId (String ObjectId)
{
this.ObjectId = ObjectId;
}
public String getAzureActiveDirectoryEventType ()
{
return AzureActiveDirectoryEventType;
}
public void setAzureActiveDirectoryEventType (String AzureActiveDirectoryEventType)
{
this.AzureActiveDirectoryEventType = AzureActiveDirectoryEventType;
}
public String getUserKey ()
{
return UserKey;
}
public void setUserKey (String UserKey)
{
this.UserKey = UserKey;
}
#Override
public String toString()
{
return "ClassPojo [UserType = "+UserType+", TargetContextId = "+TargetContextId+", RecordType = "+RecordType+", Operation = "+Operation+", Workload = "+Workload+", UserId = "+UserId+", OrganizationId = "+OrganizationId+", InterSystemsId = "+InterSystemsId+", ExtendedProperties = "+ExtendedProperties+", ActorContextId = "+ActorContextId+", CreationTime = "+CreationTime+", IntraSystemId = "+IntraSystemId+", Target = "+Target+", Actor = "+Actor+", Id = "+Id+", Version = "+Version+", ResultStatus = "+ResultStatus+", ObjectId = "+ObjectId+", AzureActiveDirectoryEventType = "+AzureActiveDirectoryEventType+", UserKey = "+UserKey+"]";
}}
Target class:
public class Target {
private String Type;
private String ID;
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
#Override
public String toString() {
return "ClassPojo [Type = " + Type + ", ID = " + ID + "]";
}}
Actor class :
public class Actor {
private String Type;
private String ID;
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
#Override
public String toString() {
return "ClassPojo [Type = " + Type + ", ID = " + ID + "]";
}}
ExtendedProperties class :
public class ExtendedProperties {
private String Name;
private String Value;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getValue() {
return Value;
}
public void setValue(String Value) {
this.Value = Value;
}
#Override
public String toString() {
return "ClassPojo [Name = " + Name + ", Value = " + Value + "]";
}}
Main class :
public class Stack {
public static void main(String[] args) {
doIt();
}
private static void doIt() {
String received = "{\"CreationTime\":\"2017-12-27T07:47:46\",\"Id\":\"10ee505b-90a4-4ac1-b96f-a6dbca939694\",\"Operation\":\"Add member to role.\",\"OrganizationId\":\"2f88f444-62da-4aae-b8af-8331a6915801\",\"RecordType\":8,\"ResultStatus\":\"success\",\"UserKey\":\"10030000A656FE5B#emumbaa10.onmicrosoft.com\",\"UserType\":0,\"Version\":1,\"Workload\":\"AzureActiveDirectory\",\"ObjectId\":\"mustafa#emumbaa10.onmicrosoft.com\",\"UserId\":\"omaji7#emumbaa10.onmicrosoft.com\",\"AzureActiveDirectoryEventType\":1,\"ExtendedProperties\":[{\"Name\":\"Role.ObjectID\",\"Value\":\"b0f54661-2d74-4c50-afa3-1ec803f12efe\"},{\"Name\":\"Role.DisplayName\",\"Value\":\"Billing Administrator\"},{\"Name\":\"Role.TemplateId\",\"Value\":\"b0f54661-2d74-4c50-afa3-1ec803f12efe\"},{\"Name\":\"Role.WellKnownObjectName\",\"Value\":\"BillingAdmins\"}],\"Actor\":[{\"ID\":\"omaji7#emumbaa10.onmicrosoft.com\",\"Type\":5},{\"ID\":\"10030000A656FE5B\",\"Type\":3},{\"ID\":\"User_d03ca514-adfa-4585-a8bd-7182a9a086c7\",\"Type\":2}],\"ActorContextId\":\"2f88f444-62da-4aae-b8af-8331a6915801\",\"InterSystemsId\":\"6d402a5b-c5de-4d9f-a805-9371c109e55f\",\"IntraSystemId\":\"a5568d01-f100-497a-b88b-c9731ff31248\",\"Target\":[{\"ID\":\"User_8f77c311-3ea0-4146-9f7d-db21bd052d3d\",\"Type\":2},{\"ID\":\"mustafa#emumbaa10.onmicrosoft.com\",\"Type\":5},{\"ID\":\"1003BFFDA67CCA03\",\"Type\":3}],\"TargetContextId\":\"2f88f444-62da-4aae-b8af-8331a6915801\"}";
JSONObject send = new JSONObject();
Gson gson = new Gson();
Input inputObject = gson.fromJson(received, Input.class);
// you can add values here and customize the output JSON
send.put("userId", inputObject.getUserId());
send.put("Workload", inputObject.getWorkload());
// read Actor list
Actor[] arr = inputObject.getActor();
for (int i = 0; i < arr.length; i++) {
// write your logic here how you want to handle the Actor list
// values
System.out.println(arr[i].getID() + " : " + arr[i].getType());
}
// read ExtendedProperties list
ExtendedProperties[] extendedProperties = inputObject.getExtendedProperties();
for (int j = 0; j < extendedProperties.length; j++) {
// write your logic here how you want to handle the
// ExtendedProperties list values
System.out.println(extendedProperties[j].getName() + " : " + extendedProperties[j].getValue());
}
System.out.println("*************");
}}
alternate main class without using POJO. Here org.json library have been used to parse the input JSON.
public class Test {
public static void main(String[] args) {
doIt();
}
private static void doIt() {
String received = "{\"CreationTime\":\"2017-12-27T07:47:46\",\"Id\":\"10ee505b-90a4-4ac1-b96f-a6dbca939694\",\"Operation\":\"Add member to role.\",\"OrganizationId\":\"2f88f444-62da-4aae-b8af-8331a6915801\",\"RecordType\":8,\"ResultStatus\":\"success\",\"UserKey\":\"10030000A656FE5B#emumbaa10.onmicrosoft.com\",\"UserType\":0,\"Version\":1,\"Workload\":\"AzureActiveDirectory\",\"ObjectId\":\"mustafa#emumbaa10.onmicrosoft.com\",\"UserId\":\"omaji7#emumbaa10.onmicrosoft.com\",\"AzureActiveDirectoryEventType\":1,\"ExtendedProperties\":[{\"Name\":\"Role.ObjectID\",\"Value\":\"b0f54661-2d74-4c50-afa3-1ec803f12efe\"},{\"Name\":\"Role.DisplayName\",\"Value\":\"Billing Administrator\"},{\"Name\":\"Role.TemplateId\",\"Value\":\"b0f54661-2d74-4c50-afa3-1ec803f12efe\"},{\"Name\":\"Role.WellKnownObjectName\",\"Value\":\"BillingAdmins\"}],\"Actor\":[{\"ID\":\"omaji7#emumbaa10.onmicrosoft.com\",\"Type\":5},{\"ID\":\"10030000A656FE5B\",\"Type\":3},{\"ID\":\"User_d03ca514-adfa-4585-a8bd-7182a9a086c7\",\"Type\":2}],\"ActorContextId\":\"2f88f444-62da-4aae-b8af-8331a6915801\",\"InterSystemsId\":\"6d402a5b-c5de-4d9f-a805-9371c109e55f\",\"IntraSystemId\":\"a5568d01-f100-497a-b88b-c9731ff31248\",\"Target\":[{\"ID\":\"User_8f77c311-3ea0-4146-9f7d-db21bd052d3d\",\"Type\":2},{\"ID\":\"mustafa#emumbaa10.onmicrosoft.com\",\"Type\":5},{\"ID\":\"1003BFFDA67CCA03\",\"Type\":3}],\"TargetContextId\":\"2f88f444-62da-4aae-b8af-8331a6915801\"}";
JSONObject send = new JSONObject();
JSONObject input = new JSONObject(received);
// you can add values here and customize the output JSON
send.put("userId", input.getString("UserId"));
send.put("Workload", input.getString("Workload"));
// read Actor list
JSONArray actorArray = input.getJSONArray("Actor");
for (int i = 0; i < actorArray.length(); i++) {
// write your logic here how you want to handle the Actor list
// values
System.out.println(
actorArray.getJSONObject(i).getString("ID") + ":" + actorArray.getJSONObject(i).getInt("Type"));
}
// read ExtendedProperties list
JSONArray extendedProperties = input.getJSONArray("ExtendedProperties");
for (int j = 0; j < extendedProperties.length(); j++) {
// write your logic here how you want to handle the
// ExtendedProperties list values
System.out.println(extendedProperties.getJSONObject(j).getString("Name") + " : "
+ extendedProperties.getJSONObject(j).getString("Value"));
}
System.out.println("*************");
}}
I am trying to read the below json data. How to read using LinkedTreeMap?
{"msgType": "gameInit", "data": {
"race": {
"track": {
"id": "indianapolis",
"name": "Indianapolis",
"pieces": [
{
"length": 100.0
},
{
"length": 100.0,
"switch": true
},
{
"radius": 200,
"angle": 22.5
}
],
"lanes": [
{
"distanceFromCenter": -20,
"index": 0
},
{
"distanceFromCenter": 0,
"index": 1
},
{
"distanceFromCenter": 20,
"index": 2
}
],
"startingPoint": {
"position": {
"x": -340.0,
"y": -96.0
},
"angle": 90.0
}
},
"cars": [
{
"id": {
"name": "Schumacher",
"color": "red"
},
"dimensions": {
"length": 40.0,
"width": 20.0,
"guideFlagPosition": 10.0
}
},
{
"id": {
"name": "Rosberg",
"color": "blue"
},
"dimensions": {
"length": 40.0,
"width": 20.0,
"guideFlagPosition": 10.0
}
}
],
"raceSession": {
"laps": 3,
"maxLapTimeMs": 30000,
"quickRace": true
}
}
}}
I've little long but working approach to parse your JSON Object using Gson.
You can try it as following:
import com.google.gson.Gson;
public class JsonParser {
public static void main(String[] args){
Gson gson = new Gson();
String yourJson = "";
MainObject object = gson.fromJson(yourJson, MainObject.class);
}
}
Here yourJson is your JSON object in which your response is received, here I've used String just to show you.
And MainObject is the POJO for required to parse your JSON object.
I've shown all POJOs for that are required for your JSON. Try to use it.
MainObject.java
public class MainObject {
private String msgType;
private Data data;
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
Data.java
public class Data {
private race race;
public race getRace() {
return race;
}
public void setRace(race race) {
this.race = race;
}
}
Track.java
public class Track{
private String id;
private String name;
private List<Pieces> pieces;
private List<Lanes> lanes;
private startingPoint startingPoint;
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<Pieces> getPieces() {
return pieces;
}
public void setPieces(List<Pieces> pieces) {
this.pieces = pieces;
}
public List<Lanes> getLanes() {
return lanes;
}
public void setLanes(List<Lanes> lanes) {
this.lanes = lanes;
}
public startingPoint getStartingPoint() {
return startingPoint;
}
public void setStartingPoint(startingPoint startingPoint) {
this.startingPoint = startingPoint;
}
}
Pieces.java
public class Pieces{
private int length;
private boolean switch;
private int radius;
private float angle;
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public float getAngle() {
return angle;
}
public void setAngle(float angle) {
this.angle = angle;
}
public boolean isSwitch() {
return Switch;
}
public void setSwitch(boolean _switch) {
Switch = _switch;
}
}
Lanes.java
public class Lanes{
private String distanceFromCenter;
private int index;
public String getDistanceFromCenter() {
return distanceFromCenter;
}
public void setDistanceFromCenter(String distanceFromCenter) {
this.distanceFromCenter = distanceFromCenter;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
StartingPoint.java
public class StartingPoint{
private String angle;
private Position position;
public String getAngle() {
return angle;
}
public void setAngle(String angle) {
this.angle = angle;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
}
Position.java
public class Position{
private String x;
private String y;
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
}
Cars.java
public class Cars{
private Id id;
private Dimensions dimensions;
public id getId() {
return id;
}
public void setId(id id) {
this.id = id;
}
public Dimensions getDimensions() {
return dimensions;
}
public void setDimensions(Dimensions dimensions) {
this.dimensions = dimensions;
}
}
Id.java
public class Id{
private String name;
private String color;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Dimensions.java
public class Dimensions{
private int length;
private int width;
private int guideFlagPosition;
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getGuideFlagPosition() {
return guideFlagPosition;
}
public void setGuideFlagPosition(int guideFlagPosition) {
this.guideFlagPosition = guideFlagPosition;
}
}
RaceSession.java
public class RaceSession{
private int lap;
private String maxLapTimeMs;
private boolean quickRace;
public int getLap() {
return lap;
}
public void setLap(int lap) {
this.lap = lap;
}
public String getMaxLapTimeMs() {
return maxLapTimeMs;
}
public void setMaxLapTimeMs(String maxLapTimeMs) {
this.maxLapTimeMs = maxLapTimeMs;
}
public boolean isQuickRace() {
return quickRace;
}
public void setQuickRace(boolean quickRace) {
this.quickRace = quickRace;
}
}
That's all. All required POJOs are here.
I've used this approach and it's working fine.
From the site:
public static void main(String[] args) {
Gson gson = new Gson();
try {
System.out.println("Reading JSON from a file");
System.out.println("----------------------------");
BufferedReader br = new BufferedReader(
new FileReader(args[0]));
//convert the json string back to object
MyBean countryObj = gson.fromJson(br, MyBean.class);
// MyBean contains the data in the JSON and is a standard Java Bean
}
}
BufferedReader in = new BufferedReader(input);
String inputLine;
String fullline = "";
while ((inputLine = in.readLine()) != null) {
fullline = fullline.concat(inputLine);
}
JSONObject rootObject = new JSONObject(fullline);
JSONObject rows1 = rootObject.getJSONObject("data");
JSONObject race = rows1.getJSONObject("race");
JSONObject track = rows1.getJSONObject("track");
JSONArray pieces = rows1.getJSONArray("pieces");
Hello This is simple you can do using JSON there is no need to use external library Gson.it can also increase the your app size.so avoid to use it.
// Try to parse JSON
try {
JSONObject jsonObjMain = new JSONObject(myjsonstring);
JSONObject jsonObjectData=(JSONObject) jsonObjMain.get("data");
JSONObject jsonObjectRace=(JSONObject) jsonObjectData.get("race");
JSONObject jsonObjectTrack=(JSONObject) jsonObjectRace.get("track");
JSONArray jsonArrayPieces=(JSONArray) jsonObjectTrack.get("pieces");
JSONArray jsonArrayLanes=(JSONArray) jsonObjectTrack.get("lanes");
JSONObject jsonObjectStartingPoint=(JSONObject) jsonObjectTrack.get("startingPoint");
System.out.println("Starting Point :"+jsonObjectStartingPoint);
JSONArray jsonArrayCars=(JSONArray) jsonObjectRace.get("cars");
JSONObject jsonObjectRaceSession=(JSONObject) jsonObjectRace.get("raceSession");
System.out.println("Race Session :"+jsonObjectRaceSession);
for (int i = 0; i < jsonArrayCars.length(); i++) {
JSONObject jsonObj = jsonArrayCars.getJSONObject(i);
JSONObject jsonObjId = (JSONObject) jsonObj.get("id");
System.out.println("id :"+jsonObjId);
JSONObject jsonObjDimensions = (JSONObject) jsonObj.get("dimensions");
System.out.println("Dinmentions :"+jsonObjDimensions);
}
for (int i = 0; i < jsonArrayPieces.length(); i++) {
JSONObject jsonObj = jsonArrayPieces.getJSONObject(i);
System.out.println("Piece data :"+jsonObj);
}
for (int i = 0; i < jsonArrayLanes.length(); i++) {
JSONObject jsonObj = jsonArrayLanes.getJSONObject(i);
System.out.println("Lanes data :"+jsonObj);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}