Android - Gson - JsonObject to class object - android

I got this JsonObject from JsonObjectRequest (im using Volley). How can I cast to Object?
{
"objects":
[
{"name":"German","id":5,},
{"name":"Cecilia","id":6,},
{"name":"Melina","id":7,},
{"name":"Karina","id":8,},
{"name":"Marcos","id":9,}
]
}
public class Invitados {
private String name;
private int id;
public Invitados(){}
public Invitados(String name, int id){
this.name=name;
this.id=id;
}
}
Thanks

Use Gson library (as you included in tags to this question) create Gson object and use its fromJson() method

You can do something like this
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject obj = (JsonObject) jsonArray.get(i);
Invitados inv = new Invitados(obj.get("name").getAsString(),obj.get("id").getAsInt());
//Doing something...
}

Related

How to parse json Data Android

How to parse the series with same title to one array list
so i got Title name with season 1 and 2
What is the best way to do it
My Json data
{
"series":[
{
"title":"Jumping cat",
"genre":"comedy",
"year":2018,
"season":1,
"imdb":7,
"info":"comdey series",
"episodes":10,
"cover":"poster"
},
{
"title":"Jumping cat",
"genre":"comedy",
"year":2019,
"season":2,
"imdb":7,
"info":"comdey series",
"episodes":11,
"cover":"poster"
}
]
}
The following code will create a "HashMap" with String keys and ArrayList values.
The ArrayList include your model for each series:
try{
JSONObject reader = new JSONObject(str);
JSONArray array = reader.optJSONArray("series");
HashMap<String, ArrayList<YourModel>> map = new HashMap<>();
for(int i=0;i<array.length();i++){
JSONObject innerObject = array.getJSONObject(i);
if(map.get(innerObject.getString("title")) != null){ // check if the title already exists, then add it to it's list
ArrayList<YourModel> arrayList = map.get(innerObject.getString("title"));
arrayList.add(new YourModel(innerObject));
}else{ // if the title does not exist, create new ArrayList
ArrayList<YourModel> arrayList = new ArrayList<>();
arrayList.add(new YourModel(innerObject));
map.put(innerObject.getString("title"),arrayList);
}
}
}catch (JSONException e){
// Do error handling
}
If you don't want to add another 3rd party. You can do this in few lines. Yes, its manual labor, but it will save a lot of bytecode added to your APK.
public class Serie {
public String title;
public String genere;
public int year;
public int season;
public int imdb;
public String info;
public int episodes;
public String cover;
public static Serie toObject(JSONObject o) throws JSONException {
Serie s = new Serie();
s.title = o.getString("title");
s.genere = o.getString("genre");
s.year = o.getInt("year");
s.season = o.getInt("season");
s.imdb = o.getInt("imdb");
s.info = o.getString("info");
s.episodes = o.getInt("episodes");
s.cover = o.getString("cover");
return s;
}
public static List<Serie> toArray(String json) throws JSONException {
JSONObject oo = new JSONObject(json);
JSONArray a = oo.getJSONArray("series");
List<Serie> l = new ArrayList<>(a.length());
for (int i =0; i<a.length(); i++ ) {
JSONObject o = a.getJSONObject(i);
l.add(Serie.toObject(o));
}
return l;
}
}
// usage
try {
List<Serie> ll = Serie.toArray(s);
System.out.println(ll.toString());
} catch (JSONException e) {
e.printStackTrace();
}
For get the information of the Json you always will need two things
POJO's the model class ob the object you will get
Choose wich one to use or JsonParser who is native of Java or Gson who is a third party
I hope this can help you :D
Your response starts with list
#SerializedName("series")
#Expose
private List<Series> series = null;
List model class
#SerializedName("title")
#Expose
private String title;
#SerializedName("genre")
#Expose
private String genre;
#SerializedName("year")
#Expose
private Integer year;
#SerializedName("season")
#Expose
private Integer season;
#SerializedName("imdb")
#Expose
private Integer imdb;
#SerializedName("info")
#Expose
private String info;
#SerializedName("episodes")
#Expose
private Integer episodes;
#SerializedName("cover")
#Expose
private String cover;
And create getter setter method
You can use Google's gson library for simply parse json into java classe and vice versa. An example for how to use gson found here

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?

How can I serialize a RealmObject to JSON in Realm for Java?

I am implementing a DB for my Application and I am trying "connect" it to my REST interface. The data comes in as JSON and with the new JSON-Support (as of Realm 0.76) I can throw the JSON at my Realm.createObjectFromJson(MyType.class, jsonString) and it creates the appropiate obejcts and RealmLists.
But how can I do the opposite? That is, take a RealmObject and serialize it to JSON? It also should serialize any RealmList inside that object.
Simply, all you need to do is:
Gson gson = //... obtain your Gson
YourRealmObject realmObj = realm.where(YourRealmObject.class).findFirst();
if(realmObj != null) {
realmObj = realm.copyFromRealm(realmObj); //detach from Realm, copy values to fields
String json = gson.toJson(realmObj);
}
to deserialize JSON into RealmObject use on of the following
say you have a class definition like this
#RealmClass
public class Foo extends RealmObject{
private String name;
public void setName(String name){ this.name = name}
public String getName(){ return this.name}
}
and a json payload like this:
String json = "{\"name\":\"bar\"}";
Foo fooObject= realm.createObjectFromJson(Foo.class, json);
//or
String jsonArray = "[{\"name\":\"bar\"},{\"name\":\"baz\"}]";
RealmList<Foo> fooObjects = realm.createAllFromJson(Foo.class, jsonArray);
However the reverse is not natively supported in realm-core. so this is how i work around it. i attempted to use GSON, but ended up writing too many codes that i myself did not understand so i implemented my own adapter like this.The problem is RealmObjects are not 'realm' java.lang.Object.
create an adapter that takes instance of your realm object and return its JSON representation.
example.
public class RealmJsonAdapter{
public JSONObject toJson(Foo foo){
JSONObject obj = new JSONObject();
obj.putString("name",foo.getName());
//if you have more fields you continue
return obj;
}
}
you can now use this adapter in your classes to serialize you RealmObject to
JSON. prefferably you would make the adapter an interface so that you let callers (might be you yourself) pass you the adapter the want to use.
you can then call say, adapter.toJSON(realmObjectInstance). and get your JSONObject implementation
after all you care only about the JSON and not the RealmObject.
NOTE
This solution is a bit oudated. RealmObjects are now real java objects so you should be able to use it with GSON with no problems. Just make sure you are using version 0.89 or later and everything will work fine.
Christian from Realm here.
Realm for Android currently doesn't have any such methods, although the core database actually supports JSON serialisation, so for now you would either have to do it manually or use a 3rd party tool like GSON (caveat, I havn't tested that scenario yet).
Following is how you would do that with GSON library.
Suppose we have the following json reply from the server :
{
   "data": [
      {
         "id": "1",
         "name": "John",
         "surname": "Doe"
      }
   ]
}
For this Json object we create a helper class with corresponding properties
public class JsonHelperClass {
String id;
String name;
String surname;
public JsonHelperClass() {
}
public JsonHelperClass(String id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
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 String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
Now in the following jsonReply is the string containing reply from server
JSONArray jsonArray = new HttpManager().getJsonArrayFromReply(jsonReply);
if(jsonArray == null || jsonArray.length <0){
return;
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = null;
try {
json = (JSONObject) array.get(i);
} catch (JSONException e) {
return null;
}
Gson gson = new Gson();
JsonHelperClass helperClass = gson.fromJson(json.toString(), JsonHelperClass.class);
createRealmObject(helperClass);
}
public void createRealmObject(JsonHelperClass helperClass){
Realm realm = Realm.getInstance(context);
realm.beginTransaction();
RealmDataObject obj = realm.createObject(RealmDataObject.class);
obj.setId(helperClass.getId());
obj.setName(helperClass.getName());
obj.setSurname(helperClass.getSurname());
realm.commitTransaction();
}
public JSONArray getJsonArrayFromReply(String reply){
JSONArray array = null;
try {
JSONObject jsonResp = new JSONObject(reply);
array = jsonResp.getJSONArray("data");
} catch (JSONException e) {
return null;
}
return array;
}
And the Realm Data Object
public class RealmDataObject extends RealmObject {
private String id;
private String name;
private String surname;
public RealmDataObject() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
Try this
private JSONArray convertRealmintoJSONArray(Activity context){
try {
RealmResults<ModelMyCart> results = RealmControllerMyCart.with(context).getBooks();
JSONArray jsonArray = new JSONArray();
for (ModelMyCart myCart : results
) {
JSONObject object = new JSONObject();
object.put(Constants.PRODUCT_ID, myCart.getId());
object.put(Constants.PRODUCT_TITLE, myCart.getProduct_title());
object.put(Constants.PRODUCT_SIZE, myCart.getProduct_size());
object.put(Constants.PRODUCT_SELLINGFEE, myCart.getProduct_sellingfee());
object.put(Constants.PRODUCT_SELLINGFEE, myCart.getShipping_price());
object.put(Constants.PRODUCT_IMAGE, myCart.getProduct_image());
object.put(Constants.PRODUCT_BRAND, myCart.getProduct_brand());
object.put(Constants.PRODUCT_CATEGORY_ID, myCart.getProduct_category_id());
object.put(Constants.PRODUCT_CATEGORY_NAME, myCart.getProduct_category_name());
object.put(Constants.PRODUCT_COLOR, myCart.getProduct_color());
object.put(Constants.PRODUCT_COLORTYPE, myCart.getProduct_colortype());
object.put(Constants.PRODUCT_CONDITION, myCart.getProduct_condition());
object.put(Constants.PRODUCT_CREATED_DATE, myCart.getProduct_created_date());
object.put(Constants.PRODUCT_MYSALEPRICE, myCart.getProduct_mysaleprice());
object.put(Constants.PRODUCT_ORIGINALPRICE, myCart.getProduct_originalprice());
object.put(Constants.PRODUCT_POTENTIALEARNINGS, myCart.getProduct_potentialearnings());
object.put(Constants.PRODUCT_SHIPPINGCHARGES, myCart.getProduct_shippingcharges());
object.put(Constants.USER_ID, myCart.getUser_id());
object.put(Constants.USER_UNAME, myCart.getUser_uname());
jsonArray.put(object);
}
Log.e("Converted",""+jsonArray);
return jsonArray;
}catch (Exception e){
}
return null;
}
For my case new Gson().toJson(realm.copy(realmObj)); causes UI freezing (sometimes out of memory exception). So I updated my Gson instance like that
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonString = gson.toJson(realm.copy(realmObj));

Parsing JSON file in android

how to parse something like this in JSON ?
{"nodes":
{"0":
{"node":{"id":"13970","name_ar":"\u0623\u062f\u0647\u0645","name_en":"Adham","bio_ar":""}},
"1":
{"node":{"id":"14033","name_ar":"aa","name_en":"Ahmed Shaalan","bio_ar":""}}}
Its not an array its more than one object, any help please ?
You can retrieve them using JSONObject. This is a very simple example, and only parses the id out of one node:
JSONObject object = new JSONObject(myJsonString);
JSONObject nodes = object.getJSONObject("nodes");
JSONObject zero = nodes.getJSONObject("0");
JSONObject myNode = zero.getJSONObject("node");
String id myNode = myNode.getString("id");
Android contains native JSON parser - it is good for small amount of data (look into package org.json ) . If you have more data to parse, some pull parser like GSON will be better.
You need to create first a class with all the variables inside the JSON. Something like this:
import java.util.HashMap;
public class NodesClass { // Create a new class called NodesClass
public Nodes nodes; // Create a new public class
public class Nodes {
public HashMap<String, InnerObject> nodes;
}
public class InnerObject {
public Node node;
public class Node {
public int id;
public String name_ar, name_en, bio_ar;
}
}
}
Ant then you need to retrieve the data. E.g something like this:
NodesClass ndes = new Gson().fromJson(stringNodes, NodesClass.class);
int[] id = new int[11];
for (int numNodes = 0; numNodes < maxNumNodes; numNodes++)
{
try {
id[numNodes] = ndes.nodes.get(String.valueOf(numNodes)).node.id;
} catch (NullPointerException n) { break; }
}
I hope it help you.
Use org.json.JSONObject class:
jObject = new JSONObject(jString);
JSONObject nodesObject = jObject.getJSONObject("nodes");
ArrayList<JSONObject> objects = new ArrayList<JSONObject>();
for( int i=0; i<10; i++)
{
objects.add(nodesObject.getJSONObject(""+i);
}
String name = objects.get(0).getJSONObject("node").getString("name_ar");
...

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