Android json objects to array list in Parcelable class - android

I don't know of the title is very accurate, but let me explain what I want.
I am having this long JSONObject (sadly it's not an array and I can't loop through it) with many other JSONObjects inside of it with similar elements (id, name, icon), and when I read through an element it writes its value in a separate class with implemented Parcelable.
Here is what my Parcelable class look like before I explain further:
public class ItemsInfo implements Parcelable {
public int itemId;
public String itemName, itemIcon;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(itemName);
dest.writeString(itemIcon);
dest.writeInt(itemId);
}
public static final Parcelable.Creator<ItemsInfo > CREATOR = new Parcelable.Creator<ItemsInfo >() {
#Override
public ItemsInfo createFromParcel(Parcel source) {
ItemsInfo ei = new ItemsInfo();
ei.itemName = source.readString();
ei.itemIcon = source.readString();
ei.itemId = source.readInt();
return ei;
}
#Override
public ItemsInfo [] newArray(int size) {
return new ItemsInfo [size];
}
};
}
what I want is everytime it reads through a JSONObject with the similar elements, to write them with an ArrayList in the String itemName, so later I can access a given item by only a index or something, and not to have to make separate strings and integers for every different item, like itemName1, itemName2, itemName3..... Is it possible?

You can use droidQuery to simplify JSON parsing. To convert your JSONObject to a Key-Value mapping, you can use this:
List<String> items = new ArrayList<String>();//this will contain your JSONObject strings
Map<String, ?> data = null;
try {
JSONObject json;//this references your JSONObject
data = $.map(json);
} catch (Throwable t) {
Log.e("JSON", "Malformed JSON Object");
}
Then, to loop through each element, just do this:
if (data != null) {
for (Map.Entry<String, ?> entry : data.entrySet()) {
items.add(entry.value().toString());
}
}
Now your List items is populated with the String representation of your JSONObejcts. Later, if you want to parse this JSON, just do:
int index = 2;//the index of the JSONObject you want
try {
Map<String, ?> data = $.map(new JSONObject(items.get(2)));
//now iterate the map
} catch (Throwable t) {
t.printStackTrace();//something wrong with your JSON string
}

Related

Parse Json response android retrofit for dynamic values

I am trying to parse JSON response in android. But not able to handle dynamic JSON format.
Here is a JSON response:
{
"code":"1",
"data":{
"220":{
"reg_no":"12",
"device_status":"off"
},
"218":{
"reg_no":"11",
"device_status":"on"
}
}
}
220 and 219 are dynamic values.
Calling API from MainActivity.java
public void getItemData() {
Call<ItemData> call = service.getItemData(token,vehicle_ids);
call.enqueue(new Callback<ItemData>() {
#Override
public void onResponse(#NonNull Call<ItemData> call,#NonNull Response<ItemData> response) {
Log.d("Response",response.body.toString());
progressDoalog.dismiss();
}
#Override
public void onFailure(#NonNull Call<ItemData> call,#NonNull Throwable t) {
progressDoalog.dismiss();
}
});
}
Create ItemData Class to handle response:
ItemData.java
public class ItemData {
private String code;
private VehicleData data = new VehicleData();
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public VehicleData getData() {
return data;
}
public void setData(VehicleData data) {
this.data = data;
}
}
VehicleData.java
public class VehicleData{
}
I am getting response:
code: 1
data : null
Please suggest me How should I change my VehicleData.java class so that I can handle
response.
The same thing can also be done using GSON, but instead of using GSON converter adapter to convert into to POJO. we will parse it manually. which gives us flexibility in case of dynamic JSON data.
let's say the JSON format is like below in my case.
{
"code":"1",
"data":{
"220":{
"reg_no":"12",
"device_status":"off"
},
"218":{
"reg_no":"11",
"device_status":"on"
}
}
}
in this case the dateWiseContent has dynamic object keys so we will parse this json string using JsonParser class.
//parsing string response to json object
JsonObject jsonObject = (JsonObject) new JsonParser().parse(resource);
//getting root object
JsonObject data = jsonObject.get("data").getAsJsonObject();
get the dynamic keys using Map.Entry as given below
// your code goes here
for (Map.Entry<String, JsonElement> entry : data.entrySet()) {
//this gets the dynamic keys
String dateKey = entry.getKey();
//you can get any thing now json element,array,object according to json.
JsonArray jsonArrayDates = entry.getValue().getAsJsonArray();
int appointmentsSize = jsonArrayDates.size();
for (int count = 0; count < appointmentsSize; count++) {
JsonObject objectData = jsonArrayDates.get(count).getAsJsonObject();
String device_status = objectData.get("device_status").getAsString();
}
}
similarly any level of dynamic json can be parsed using Map.Entry
I solved this using Hashmap.
public class ItemData {
Hashmap<String, object> data = new hashmap<>();
}
and using getter setter I can access variables.

Gson with complicated Json Android Studio

My Json file is
{"code":0,"datas":[{"id":0,"target_id":0},{"id":1,"target_id":0
}................]}
And what I wrote is..
// String data;
// data has the Json as String
JsonParser jsonParser = new JsonParser();
JsonObject object = (JsonObject) jsonParser.parse(data);
JsonArray memberArray = (JsonArray) object.get("datas");
JsonObject object1= (JsonObject) memberArray.get(0);
dataParsed = object1.get("id").getAsString();
// wanted print 1
And it's not working..
As I guess it's something different with normal Json on Internet.
I thought "code" : 0 is the problem
I want to know how to seperate this json code / data and get id and target id String
Your JSON contains an integer ("code") plus an array. the array itself contains a number of JSON objects. First, extract a JSON object and an array, then extract JSON objects from the array.
My solution for storing these data is based on object-oriented programming. Create a Java object with two variables called DataObject. An integer for "code" and a list of another Java object called IdPair for storing "id" and "target_id". First, define the classes. IdPair object class:
public class IdPair {
int id;
int target_id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTarget_id() {
return target_id;
}
public void setTarget_id(int target_id) {
this.target_id = target_id;
}
}
DataObject class:
public class DataObject {
private int code;
private List<IdPair> idPairs;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public List<IdPair> getIdPairs() {
return idPairs;
}
public void setIdPairs(List<IdPair> idPairs) {
this.idPairs = idPairs;
}
}
then start extracting data from your json:
DataObject dataObject = new dataObject(); // init object
JSONObject jsonObject = new JSONObject(data); // whole json is an object! (data is your json)
int code = jsonObject.optInt("code"); // get code from main json
dataObject.setCode(code); // set code to our object
List<IdPair> pairs = new ArrayList<>(); // init list of id pairs
JSONArray datas = jsonObject.optJSONArray("datas"); // get json array from main json
IdPair pair = null; // define idPairs object
for (int i=0; i<datas.length() ; i++){ // jasonArray loop
JSONObject object = new JSONObject(datas(i)); // each jsonObject in the jsonArray
pair = new IdPair();// init idPair
int id = object.optInt("id"); // get the object id
int targetId = object.optInt("target_id"); // get the object target_id
// set values to our object
pair.setId(id);
pair.setTarget_id(targetId);
//add object to list
pairs.add(pair);
}
// your dataObject is now filled with JSON data
Note: this is a general solution. For example, you could use a HashMap instead of IdPair object.
Here you can do the following code for obtaining id and target_id values from your json:
JsonParser jsonParser = new JsonParser();
JsonObject object = (JsonObject) jsonParser.parse(new String(Files.readAllBytes(Paths.get("test.json"))));
JsonArray memberArray = (JsonArray) object.get("datas");
for (JsonElement jsonElement : memberArray) {
System.out.println(
String.format("Id : %d TId: %d",
jsonElement.getAsJsonObject().get("id").getAsInt(),
jsonElement.getAsJsonObject().get("target_id").getAsInt()));
}
Output is:
Id : 0 TId: 0
Id : 1 TId: 0

How do I convert an object that contains and arraylist of other objects into JSON for sending to an API - Android

Imagine I have an object - ChildObject. ChildObject has 3 properties. Id, Name, Age.
I also have another object - ParentObject. ParentObject also has 3 properties. Id, Date but the 3rd is ArrayList of ChildObjects Family.
How would I go about converting this into a JSONObject to be able to send it over to a RESTfull WebAPI service.
So far I have failed to find anything that works, and I'm struggling to wrap my head around the problem.
To make it more of a challenge I cant use 3rd party extentions (eg gson etc).
Thanks in advance for your help.
Adding Objects to see if they make it any clearer
ParentObject
public class JobMovementRequestDto {
public String Id_Employee;
public String ActionDate;
public String Id_Terminal;
public String Id_Device;
public ArrayList<JobActivityRequestDto> FromJobs;
public ArrayList<JobActivityRequestDto> ToJobs;
public JobMovementRequestDto(){
}
public JobMovementRequestDto(String idEmployee, String activityDate, String idTerminal, String idDevice, ArrayList<JobActivityRequestDto> fromItems, ArrayList<JobActivityRequestDto> toItems){
this.Id_Employee = idEmployee;
this.ActionDate = activityDate;
this.Id_Terminal = idTerminal;
this.Id_Device = idDevice;
this.FromJobs = fromItems;
this.ToJobs = toItems;
}
public String getIdEmployee() {return this.Id_Employee;}
public String getActivityDate() {return this.ActionDate;}
public String getIdTerminal() {return this.Id_Terminal;}
public String getIdDevice() {return this.Id_Device;}
public ArrayList<JobActivityRequestDto> getFromList() {return this.FromJobs;}
public ArrayList<JobActivityRequestDto> getToLIst() { return this.ToJobs;}
ChildObject
public class JobActivityRequestDto {
public String Id_Job;
public String Id_Batch;
public String Id_ActivityType;
public JobActivityRequestDto()
{
}
public JobActivityRequestDto(String idJob, String idBatch, String idActivityType)
{
this.Id_Job = idJob;
this.Id_Batch = idBatch;
this.Id_ActivityType = idActivityType;
}
public String getIdJob() { return this.Id_Job;}
public String getIdBatch() {return this.Id_Batch;}
public String getIdActivityType() {return this.Id_ActivityType;}
}
Here is your complete solution, Please check.
public void makeJsonObject()
{
try
{
JSONObject parentJsonObject = new JSONObject();
parentJsonObject.put("Id", parentObject.getId());
parentJsonObject.put("Id", parentObject.getDate());
JSONArray childListArr = new JSONArray();
for (int i = 0; i < parentObject.ChildObjectsList().size(); i++)
{
ChildObject childObject = parentObject.ChildObjectsList().get(i);
JSONObject childJsonObject = new JSONObject();
childJsonObject.put("id", childObject.getId());
childJsonObject.put("Name", childObject.getName());
childJsonObject.put("Age", childObject.getAge());
childListArr.put(childJsonObject);
}
parentJsonObject.put("childList", childListArr);
Log.e(TAG, "parentJsonObject=="+parentJsonObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
JSONObject fromObject, toObject, parentObject;
JSONArray fromArray, toArray;
JobMovementRequestDto JMRD = new JobMovementRequestDto();
try {
parentObject = new JSONObject();
parentObject.put("Id_Employee", JMRD.getIdEmployee());
parentObject.put("ActionDate", JMRD.getActivityDate());
parentObject.put("Id_Terminal", JMRD.getIdTerminal());
parentObject.put("Id_Device", JMRD.getIdDevice());
fromArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getFromList()){
//Loop your multiple childObjects and add it childArray
fromObject = new JSONObject();
fromObject.put("Id_Job",JARD.getIdJob());
fromObject.put("Id_Batch",JARD.getIdBatch());
fromObject.put("Id_ActivityType",JARD.getIdActivityType());
fromArray.put(fromObject);
}
toArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getToLIst()){
//Loop your multiple childObjects and add it childArray
toObject = new JSONObject();
toObject.put("Id_Job",JARD.getIdJob());
toObject.put("Id_Batch",JARD.getIdBatch());
toObject.put("Id_ActivityType",JARD.getIdActivityType());
toArray.put(toObject);
}
//Finally, Add childArray to ParentObject.
parentObject.put("fromObjects",fromArray);
parentObject.put("toObjects",toArray);
} catch (JSONException e) {
e.printStackTrace();
}
Create a JSON like this and You Can Send This to Your Server. I Hope This Is What You Want Right?

Deserializing multi-leveled JSON

I am completely new to the concept of JSON, and am having trouble figuring out how to deserialize a multi-leveled JSON statement using Gson.
This is what I'm trying to deserialize: {"stat":"ok","pkey":{"id":"1234567890"}}
First I tried doing using a hashmap:
HashMap<String, Object> results = gson.fromJson(response, HashMap.class);
The result looked reasonable enough, but the second entry in the hashmap (the one that contained the actual id number) was a gson.internal.LinkedTreeMap, which I couldn't access.
Next I tried making a custom class to deserialize it into, but I can't seem to get it to work right...
Neither of these worked:
class Results
{
String stat;
String[][] pkey;
}
class Results
{
String stat;
String[] pkey;
}
The only examples I can find online have to do with deserializing simple, one level JSON, which looks easy. I just can't seem to figure this out.
Use JSONObject can easy deserializing multi-leveled JSON
This is Log "ok" and "1234567890" from your example
String json = "{\"stat\":\"ok\",\"pkey\":{\"id\":\"1234567890\"}}";
try {
JSONObject jsonObj = new JSONObject(json);
Log.i("chauster", jsonObj.getString("stat"));
Log.i("chauster", jsonObj.getJSONObject("pkey").getString("id"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is code for gson, you need to custom your class
public class Custom {
private String stat;
private IdClass pkey;
public String getStat() {
return stat;
}
public IdClass getPkey() {
return pkey;
}
public Custom(String _stat, IdClass _pkey) {
stat = _stat;
pkey = _pkey;
}
public class IdClass {
private String id;
public String getId() {
return id;
}
public IdClass(String _id){
id = _id;
}
}
}
String json = "{\"stat\":\"ok\",\"pkey\":{\"id\":\"1234567890\"}}";
Gson gson = new Gson();
Custom custom = gson.fromJson(json, Custom.class);
System.out.println(custom.getStat());
System.out.println(custom.getPkey().getId());

gson to POJO object, not working properly

I am developing an Android application and I access a RESTfull web service that returns a JSON. This JSON I want to put it in POJOs but I think I am missing something as it doesn't work.
The JSON retuned is as follow:
[{"CategoryName":"Food","Id":1},{"CategoryName":"Car","Id":2},{"CategoryName":"House","Id":3},{"CategoryName":"Work","Id":4}]
this is returned in response variable
String response = client.getResponse();
And now I try the following:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
JSONObject j;
MainCategories cats = null;
try
{
j = new JSONObject(response);
cats = gson.fromJson(j.toString(), MainCategories.class);
}
catch(Exception e)
{
e.printStackTrace();
}
The error I get is:
09-02 07:06:47.009:
WARN/System.err(568):
org.json.JSONException: Value
[{"Id":1,"CategoryName":"Food"},{"Id":2,"CategoryName":"Car"},{"Id":3,"CategoryName":"House"},{"Id":4,"CategoryName":"Work"}]
of type org.json.JSONArray cannot be
converted to JSONObject
09-02 07:06:47.029:
WARN/System.err(568): at
org.json.JSON.typeMismatch(JSON.java:107)
Here are the POJO objects
MainCategories.java
public class MainCategories {
private List<CategoryInfo> category;
public List<CategoryInfo> getCategory() {
if (category == null) {
category = new ArrayList<CategoryInfo>();
}
return this.category;
}
}
CategoryInfo.java
public class CategoryInfo {
public String categoryName;
public Integer id;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String value) {
this.categoryName = ((String) value);
}
public Integer getId() {
return id;
}
public void setId(Integer value) {
this.id = value;
}
}
To access the web service I use the class from: http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
Please help me as I am stuck for 2 days now and can't figure out how to continue. I found some subjects here but still didn't found a way around. Thank you very much.
Top level entity in your JSON string is JSONArray not JSONObject, while you're trying to parse it as object. Create an array from the string and use that.
JSONArray array = new JSONArray(response);

Categories

Resources