Deserialization of JSON webservice in Android - android

I am trying to deserialize this JSON array into my android project.
[{"Name":"Ban","Price":1},{"Name":"Banana","Price":1},{"Name":"chicken","Price":14},{"Name":"pizza","Price":16},{"Name":"slice","Price":1}]
I have made this webservice in Asp.net.
The code I am using to deserialize it is below
public void onClick(View v)
{
String url="http://192.168.15.2/MyAndroid/InputCaller.aspx"; //do not use localhost
String response=callWebService(url);
List<Items> mObjectList = new ArrayList<Items>() ;
ItemsList list = null;
Gson gson = new Gson();
list = gson.fromJson(response, ItemsList.class);
// list = getItemsList(response);
Intent myIntent = new Intent(v.getContext(), Cart.class);
startActivity(myIntent);
}
public final ItemsList getItemsList (String jsonString)
{
ItemsList il = null;
Gson gson = new Gson();
il = gson.fromJson(jsonString, ItemsList.class);
return il;
}
public class ItemsList
{
private List<ItemsContainer> items = new ArrayList<ItemsContainer>();
public List<ItemsContainer> getItemsContainerList()
{
return items;
}
}
class ItemsContainer
{
Items items;
public Items getItem()
{
return items;
}
}
public class Items
{
String Name;
int Price;
}
It is not working and when I try to debug it I get this message on list = gson.fromJson(response, ItemsList.class);
Gson.class Source not found.
This is my first deserialisation program and I would really appreciate if anybody help me with it. Thank you,

Don't make things complicated by using further parent classes (as container) for Items class. Simply de-serialize all the items into a List object using Gson as below:
List<Items> listItems = (List<Items>) gson.fromJson(response,
new TypeToken<List<Items>>(){}.getType());
now you've got all the Items in a List object: listItems

Related

ArrayList cannot be set to model class

I am new to android.I have a JSONArray containing images and other attributes.I am trying to set it into the model class.
MenuContent singleItem = new MenuContent();
singleItem.setContent(mContentJsonObject.getString(AppConstants.APIKeys.CONTENT));
singleItem.setContentId(mContentJsonObject.getString(AppConstants.APIKeys.PARAGRAPH_ID));
singleItem.setChapterId(mContentJsonObject.getString(AppConstants.APIKeys.CHAPTER_ID));
singleItem.setClassId(getSharedPreference(AppConstants.APIKeys.CLASS_ID));
singleItem.setLanguageId(getSharedPreference(AppConstants.APIKeys.LANGUAGE_ID));
JSONArray mGalleryimages = mContentJsonObject.getJSONArray(AppConstants.APIKeys.PARAGRAPH_GALLERY_IMAGES);
for (int k = 0; k < mGalleryimages.length(); k++) {
JSONObject mGallerycontent=mGalleryimages.getJSONObject(k);
ImageGallery imageGallery = new ImageGallery();
imageGallery.setImageId(String.valueOf(k));
imageGallery.setImagePath(mGallerycontent.getString(AppConstants.APIKeys.PARAGRAPH_GALLERY_CONTENT));
array_image.add(imageGallery);
}
singleItem.setImageGallery(array_image);
singleItem.save();
mParagraphsList.add(singleItem);
The problem is I can set all attributes except galleryimages array to the model class.But setImageGallery only is not working.I am getting null there when debugging it.This is MenuContent model class snippet
ArrayList <ImageGallery> imageGallery;
public ArrayList<ImageGallery> getImageGallery() {
return imageGallery;
}
public void setImageGallery(ArrayList<ImageGallery> imageGallery) {
this.imageGallery = imageGallery;
}
ImageGallery model class snippet
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getImagePath() {
return imagePath;
}
Can anyone tell me whats the problem?Any help is appreciated.
This code can be converted to 2 lines with well known Google Gson Library
Have a glance at this.
Type listType = new TypeToken<List<MenuContent>>() {}.getType();
List<MenuContent> yourList = new Gson().fromJson(yourJson, listType);
You dont have to write a long code with parsing with keys.

how to adapt the data from global object to spinner

I have my GlobalClass extends Application class. I want to bind the global object data to spinner. Here is my GlobalClass
public class GlobalClass extends Application {
private List<ProjectType> projectTypes;
public List<ProjectType> getProjectTypes() {
return projectTypes;
}
public void setProjectTypes(List<ProjectType> projectTypes) {
this.projectTypes = projectTypes;
}
}
Pojo class
public class ProjectType implements Serializable {
private Integer projectTypeId;
private String typeName;
private Integer peckOrder;
//getter and setter here
And I get the response from the server using volley and parse using GSON and set the response to GlobalClass
here the code
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getString(R.string.TEST_projectTypeURL), null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
Gson gson = new Gson();
List<ProjectType> projectTypes = gson.fromJson(String.valueOf(response),List.class);
globalVariable.setProjectTypes(projectTypes);
}
}
And finally in another activity class iam using spinner to bind the data from the GlobalClass object
globalVariable = (GlobalClass) getApplicationContext();
List<String> projectTypeList = new ArrayList<>();
ArrayList<ProjectType> projectTypesCollection = new ArrayList<ProjectType>(globalVariable.getProjectTypes());
for (ProjectType projectType: projectTypesCollection) {
projectTypeList.add(projectType.getTypeName());
}
prjtTypeSpinner = (Spinner)findViewById(R.id.spn_prjt_type);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,projectTypeList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
prjtTypeSpinner.setAdapter(dataAdapter);
While trying the above code I am getting an error "com.google.gson.internal.LinkedTreeMap cannot be cast to the pojo.ProjectType class"
here the object return value,
[{projectTypeId=3.0, typeName=ALS, peckOrder=220.0}, {projectTypeId=2.0, typeName=ALB, peckOrder=210.0}, {projectTypeId=1.0, typeName=CL, peckOrder=200.0}, {projectTypeId=7.0, typeName=ACG, peckOrder=40.0}, {projectTypeId=6.0, typeName=ACS, peckOrder=30.0}, {projectTypeId=5.0, typeName=ACB, peckOrder=20.0}, {projectTypeId=4.0, typeName=CC, peckOrder=10.0}]
I want the typeName in spinner. Thanks in advance.
I finally solve this problem,
Arrays.asList(gson.fromJson(response, ProjectType[].class))
when I try the code my error get resolved, this code work well
I think you have problem with this codes
List<ProjectType> projectTypes = gson.fromJson(String.valueOf(response),List.class);
you need to change to:
List<ProjectType> projectTypes = gson.fromJson(new Gson().toJson(response),new TypeToken<List<ProjectType>>() {
}.getType());

Generic Method to Save and Retrieve List of Custom Objects in Shared Preference

There are many SO question asked related to this topic but all discuss specific Type of Custom object List storing or retrieving in shared prefs,
But my question is about how to store any kind of Object List in shared prefs:
My Attempt(almost same as in TinyDB):
Store:
public void putListObject(String key, ArrayList<Object> objArray){
Gson gson = new Gson();
ArrayList<String> objStrings = new ArrayList<String>();
for(Object obj : objArray){
objStrings.add(gson.toJson(obj));
}
preferences.edit().putString(key, objStrings).apply();
}
Get
public List<Object> getListObject(String key, Class<?> mClass){
Gson gson = new Gson();
List<String> objStrings = new ArrayList<String>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
List<Object> objects = new ArrayList<Object>();
for(String jObjString : objStrings){
Object value = gson.fromJson(jObjString, mClass);
objects.add(value);
}
return objects;
}
Problem in the above code is, it stores value in shared prefs , but cannot get it back as expected.
Expected Behavior:
class myClass{
int i;
}
List<myClass> mc = new ArrayList();
// Store:
putListObject("KEY",mc);
// GET:
List<myClass> tr = getListObject("KEY",myClass.class); // error here
In your getListObject method, you're returning a List of plain Object whereas tr in this line List<myClass> tr = getListObject("KEY",mc.myClass.class); accepts List of myClass objects.
I was also struggling with TinyDB implementation, but I was able to resolve the getListObject and putListObject as follows:
public <T> ArrayList<T> getListObject(String key, Class<T> mClass){
Gson gson = new Gson();
ArrayList<String> objStrings = getListString(key);
ArrayList<T> objects = new ArrayList<T>();
for(String jObjString : objStrings){
T value = gson.fromJson(jObjString, mClass);
objects.add(value);
}
return objects;
}
public <T> void putListObject(String key, ArrayList<T> objArray){
checkForNullKey(key);
Gson gson = new Gson();
ArrayList<String> objStrings = new ArrayList<String>();
for(T obj : objArray){
objStrings.add(gson.toJson(obj));
}
putListString(key, objStrings);
}
Notice I used generics instead of type Object.
Hope this helps!

Flatten Nested Object into target object with GSON

Dearest Stackoverflowers,
I was wondering if anyone knows how to solve this the best way;
I'm talking to an api which returns a json object like this:
{
"field1": "value1",
"field2": "value2",
"details": {
"nested1": 1,
"nested2": 1
}
In java I have an object (entity) which for example, would have all these fields, but with the details as loose fields, so:
field1, field2, nested1, nested2.
This because It's an android project and I can't just go saving a class with info into my entity since I'm bound to ormlite.
Is there any way to convert the fields flat into my object using GSON? note that I'm using a generic class to convert these right now straight from the API. And I want to store these fields (which contain information as an int). In the same entity.
You can write a custom type adapter to map json value to your pojo.
Define a pojo:
public class DataHolder {
public List<String> fieldList;
public List<Integer> detailList;
}
Write a custom typeAdapter:
public class CustomTypeAdapter extends TypeAdapter<DataHolder> {
public DataHolder read(JsonReader in) throws IOException {
final DataHolder dataHolder = new DataHolder();
in.beginObject();
while (in.hasNext()) {
String name = in.nextName();
if (name.startsWith("field")) {
if (dataHolder.fieldList == null) {
dataHolder.fieldList = new ArrayList<String>();
}
dataHolder.fieldList.add(in.nextString());
} else if (name.equals("details")) {
in.beginObject();
dataHolder.detailList = new ArrayList<Integer>();
} else if (name.startsWith("nested")) {
dataHolder.detailList.add(in.nextInt());
}
}
if(dataHolder.detailList != null) {
in.endObject();
}
in.endObject();
return dataHolder;
}
public void write(JsonWriter writer, DataHolder value) throws IOException {
throw new RuntimeException("CustomTypeAdapter's write method not implemented!");
}
}
Test:
String json = "{\"field1\":\"value1\",\"field2\":\"value2\",\"details\":{\"nested1\":1,\"nested2\":1}}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(DataHolder.class, new CustomTypeAdapter());
Gson gson = builder.create();
DataHolder dataHolder = gson.fromJson(json, DataHolder.class);
Output:
About TypeAdapter:
https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html
http://www.javacreed.com/gson-typeadapter-example/

How to store a value in HashMap (Android)?

im worked in soap message, using SAXparser to retrieve the value(from Webservice) stored in ArrayList and the ArrayList working fine, but i want to store in HashMap, because Using key to identify a each name has certain SystemId, Please any one help me
Thanks
I tried the code:
public class SitesList
{
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> systemid = new ArrayList<String>();
//Map <String,String> map = new HashMap<String,String>();
public ArrayList<String> getName()
{
return name;
}
public void setName(String nameString)
{
this.name.add(nameString);
System.out.println("name "+ name);
}
public ArrayList<String> getSystemId()
{
return systemid;
}
public void setSystemId(String systemidString)
{
this.systemid.add(systemidString);
System.out.println("systemid "+systemid);
}
you can store like this way
you arraylist for name
private ArrayList<String> name = new ArrayList<String>();
and HashMap like this way
HashMap<String, ArrayList<String>>h = new HashMap<String, ArrayList<String>>();
and you can store your arraylist like this way
h.put("name", name);
If you don't need to preserve the order of entries, you can do something like this:
public class SitesList {
private final Map <String,String> map = new HashMap<String,String>();
public Set<String> getNames() {
return map.keySet();
}
public void add(String nameString, String systemidString) {
map.put(nameString, systemidString);
}
public Collection<String> getSystemIds() {
return map.values(); // may contain duplicates
}
}

Categories

Resources