GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"? - java

I'm trying to parse a JSON string like this one
[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
into a list of objects.
List<ChannelSearchEnum> lcs = (List<ChannelSearchEnum>) new Gson().fromJson( jstring , ChannelSearchEnum.class);
Here's an object class I'm using.
import com.google.gson.annotations.SerializedName;
public class ChannelSearchEnum {
#SerializedName("updated_at")
private String updated_at;
#SerializedName("fetched_at")
private String fetched_at;
#SerializedName("description")
private String description;
#SerializedName("language")
private String language;
#SerializedName("title")
private String title;
#SerializedName("url")
private String url;
#SerializedName("icon_url")
private String icon_url;
#SerializedName("logo_url")
private String logo_url;
#SerializedName("id")
private String id;
#SerializedName("modified")
private String modified;
public final String get_Updated_at() {
return this.updated_at;
}
public final String get_Fetched_at() {
return this.fetched_at;
}
public final String get_Description() {
return this.description;
}
public final String get_Language() {
return this.language;
}
public final String get_Title() {
return this.title;
}
public final String get_Url() {
return this.url;
}
public final String get_Icon_url() {
return this.icon_url;
}
public final String get_Logo_url() {
return this.logo_url;
}
public final String get_Id() {
return this.id;
}
public final String get_Modified() {
return this.modified;
}
}
But it throws me with
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
Any ideas how should I fix it?

The problem is you're telling Gson you have an object of your type. You don't. You have an array of objects of your type. You can't just try and cast the result like that and expect it to magically work ;)
The User guide for Gson Explains how to deal with this:
https://github.com/google/gson/blob/master/UserGuide.md
This will work:
ChannelSearchEnum[] enums = gson.fromJson(yourJson, ChannelSearchEnum[].class);
But this is better:
Type collectionType = new TypeToken<Collection<ChannelSearchEnum>>(){}.getType();
Collection<ChannelSearchEnum> enums = gson.fromJson(yourJson, collectionType);

The problem is that you are asking for an object of type ChannelSearchEnum but what you actually have is an object of type List<ChannelSearchEnum>.
You can achieve this with:
Type collectionType = new TypeToken<List<ChannelSearchEnum>>(){}.getType();
List<ChannelSearchEnum> lcs = (List<ChannelSearchEnum>) new Gson()
.fromJson( jstring , collectionType);

In my case JSON string:
[{"category":"College Affordability",
"uid":"150151",
"body":"Ended more than $60 billion in wasteful subsidies for big banks and used the savings to put the cost of college within reach for more families.",
"url":"http:\/\/www.whitehouse.gov\/economy\/middle-class\/helping middle-class-families-pay-for-college",
"url_title":"ending subsidies for student loan lenders",
"type":"Progress",
"path":"node\/150385"}]
and I print "category" and "url_title" in recycleview
Datum.class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Datum {
#SerializedName("category")
#Expose
private String category;
#SerializedName("uid")
#Expose
private String uid;
#SerializedName("url_title")
#Expose
private String urlTitle;
/**
* #return The category
*/
public String getCategory() {
return category;
}
/**
* #param category The category
*/
public void setCategory(String category) {
this.category = category;
}
/**
* #return The uid
*/
public String getUid() {
return uid;
}
/**
* #param uid The uid
*/
public void setUid(String uid) {
this.uid = uid;
}
/**
* #return The urlTitle
*/
public String getUrlTitle() {
return urlTitle;
}
/**
* #param urlTitle The url_title
*/
public void setUrlTitle(String urlTitle) {
this.urlTitle = urlTitle;
}
}
RequestInterface
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by Shweta.Chauhan on 13/07/16.
*/
public interface RequestInterface {
#GET("facts/json/progress/all")
Call<List<Datum>> getJSON();
}
DataAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Shweta.Chauhan on 13/07/16.
*/
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder>{
private Context context;
private List<Datum> dataList;
public DataAdapter(Context context, List<Datum> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.data,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.categoryTV.setText(dataList.get(position).getCategory());
holder.urltitleTV.setText(dataList.get(position).getUrlTitle());
}
#Override
public int getItemCount() {
return dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView categoryTV, urltitleTV;
public MyViewHolder(View itemView) {
super(itemView);
categoryTV = (TextView) itemView.findViewById(R.id.txt_category);
urltitleTV = (TextView) itemView.findViewById(R.id.txt_urltitle);
}
}
}
and finally MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DataAdapter dataAdapter;
private List<Datum> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView=(RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
loadJSON();
}
private void loadJSON(){
dataArrayList = new ArrayList<>();
Retrofit retrofit=new Retrofit.Builder().baseUrl("https://www.whitehouse.gov/").addConverterFactory(GsonConverterFactory.create()).build();
RequestInterface requestInterface=retrofit.create(RequestInterface.class);
Call<List<Datum>> call= requestInterface.getJSON();
call.enqueue(new Callback<List<Datum>>() {
#Override
public void onResponse(Call<List<Datum>> call, Response<List<Datum>> response) {
dataArrayList = response.body();
dataAdapter=new DataAdapter(getApplicationContext(),dataArrayList);
recyclerView.setAdapter(dataAdapter);
}
#Override
public void onFailure(Call<List<Datum>> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
}
}

Alternative could be
to make your response look like
myCustom_JSONResponse
{"master":[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
}
instead of
server_JSONResponse
[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
CODE
String server_JSONResponse =.... // the string in which you are getting your JSON Response after hitting URL
String myCustom_JSONResponse="";// in which we will keep our response after adding object element to it
MyClass apiResponse = new MyClass();
myCustom_JSONResponse="{\"master\":"+server_JSONResponse+"}";
apiResponse = gson.fromJson(myCustom_JSONResponse, MyClass .class);
After this it will be just any other GSON Parsing

This looks like a Json array list.Therefore its best to use ArrayList to handle the data. In your api end point add array list like this
#GET("places/")
Call<ArrayList<Place>> getNearbyPlaces(#Query("latitude") String latitude, #Query("longitude") String longitude);

according to GSON User guide, you cannot.
Collections Limitations
Can serialize collection of arbitrary objects but can not deserialize from it. Because there is no way for the user to indicate the type of the resulting object

Kotlin:
var list=ArrayList<Your class name>()
val listresult: Array<YOUR CLASS NAME> = Gson().fromJson(
YOUR JSON RESPONSE IN STRING,
Array<Your class name>:: class.java)
list.addAll(listresult)

You need to let Gson know additional type of your response as below
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;
Type collectionType = new TypeToken<List<UserSite>>(){}.getType();
List<UserSite> userSites = gson.fromJson( response.getBody() , collectionType);

I am not sure if this is the best way to use GSON, but works for me. You can use some like this on the MainActivity:
public void readJson() {
dataArrayList = new ArrayList<>();
String json = "[\n" + IOHelper.getData(this) + "\n]\n";
Log.d(TAG, json);
try{
JSONArray channelSearchEnums = new JSONArray(json);
for(int i=0; i< channelSearchEnums.length(); i++)
{
JSONObject enum = channelSearchEnums.getJSONObject(i);
ChannelSearchEnum channel = new ChannelSearchEnum(
enum.getString("updated_at"), enum.getString("fetched_at"),
enum.getString("description"), enum.getString("language"),
enum.getString("title"), enum.getString("url"),
enum.getString("icon_url"), enum.getString("logo_url"),
enum.getString("id"), enum.getString("modified"))
dataArrayList.add(channel);
}
//The code and place you want to show your data
}catch (Exception e)
{
Log.d(TAG, e.getLocalizedMessage());
}
}
You only have strings, but if you would have doubles or int, you could put getDouble or getInt too.
The method of IOHelper class is the next (Here, the path is save on the internal Storage):
public static String getData(Context context) {
try {
File f = new File(context.getFilesDir().getPath() + "/" + fileName);
//check whether file exists
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (IOException e) {
Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
return null;
}
}
If you want more information about this, you can see this video, where I get the code of readJson(); and this thread where I get the code of getData().

public ChannelSearchEnum[] getChannelSearchEnum(Response response) {
return response.as(ChannelSearchEnum[].class, ObjectMapperType.GSON);
}
Above will solve and passing response will returned mapped object array of the class

Solution
I am using volley library. I parse response automatic in volley using GSON
[
{
"name": "Naruto: Shippuuden",
"description": "It has been two and a half years since Naruto Uzumaki left Konohagakure, the Hidden Leaf Village, for intense training following events which fueled his desire to be stronger. Now Akatsuki, the mysterious organization of elite rogue ninja, is closing in on their grand plan which may threaten the safety of the entire shinobi world.",
"Rating": "8.16",
"episode": 500,
"categorie":"Animation | Drama | Adventure",
"studio":"Studio Pierrot",
"img": "https://myanimelist.cdn-dena.com/images/anime/5/17407.jpg"
},
{
"name": "One Piece",
"description": "Gol D. Roger was known as the 'Pirate King',the strongest and most infamous being to have sailed the Grand Line. The capture and death of Roger by the World Government brought a change throughout the world. His last words before his death revealed the existence of the greatest treasure in the world, One Piece. It was this revelation that brought about the Grand Age of Pirates, men who dreamed of finding One Piece—which promises an unlimited amount of riches and fame—and quite possibly the pinnacle of glory and the title of the Pirate King.",
"Rating": "8.54",
"episode": 700,
"categorie":"Animation | Drama | Adventure",
"studio":"Toei Animation",
"img": "https://myanimelist.cdn-dena.com/images/anime/6/73245.jpg"
}
]
2.This my model
public class DataResponse implements Serializable {
#SerializedName("studio")
private String studio;
#SerializedName("img")
private String img;
#SerializedName("categorie")
private String categorie;
#SerializedName("Rating")
private String rating;
#SerializedName("name")
private String name;
#SerializedName("description")
private String description;
#SerializedName("episode")
private int episode;
public void setStudio(String studio){
this.studio = studio;
}
public String getStudio(){
return studio;
}
public void setImg(String img){
this.img = img;
}
public String getImg(){
return img;
}
public void setCategorie(String categorie){
this.categorie = categorie;
}
public String getCategorie(){
return categorie;
}
public void setRating(String rating){
this.rating = rating;
}
public String getRating(){
return rating;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setDescription(String description){
this.description = description;
}
public String getDescription(){
return description;
}
public void setEpisode(int episode){
this.episode = episode;
}
public int getEpisode(){
return episode;
}
#Override
public String toString(){
return
"Response{" +
"studio = '" + studio + '\'' +
",img = '" + img + '\'' +
",categorie = '" + categorie + '\'' +
",rating = '" + rating + '\'' +
",name = '" + name + '\'' +
",description = '" + description + '\'' +
",episode = '" + episode + '\'' +
"}";
}
}
my api method
define globle
private List<DataResponse> dataResponses = new ArrayList<>();
private void volleyAutomation(String url) {
JSONArray array = new JSONArray();
JsonArrayRequest request_json = new JsonArrayRequest(Request.Method.GET, url, array,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
dataResponses = Arrays.asList(gson.fromJson(response.toString(), DataResponse[].class));
rvList(dataResponses);
Log.d("respknce___", String.valueOf(dataResponses.size()));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request_json);
}

Related

Java GSON Error: JSON document was not fully consumed

So I have a JSON document that I want to read with different values including array like below
{ "name": "MacBook", "price": 1299, "stock": 10, "picture": "macbook.jpeg", "categories": [{"id": 1,"name": "macbook"},{"id": 2, "name":"notebook"}]}
I created a couple of POJO java classes to read them:
1 - Class (Product.java)
package models;
import java.util.ArrayList;
public class Product {
String name;
int price;
int stock;
String picture;
public ArrayList<Categories> categories;
public Product(String name, int price, int stock, String picture) {
this.name = name;
this.price = price;
this.stock = stock;
this.picture = picture;
this.categories = new ArrayList<>();
}
public void setName(String name) {
this.name = name;
}
public void setPrice(int price) {
this.price = price;
}
public void setStock(int stock) {
this.stock = stock;
}
public void setPicture(String picture) {
this.picture = picture;
}
public void setCategories(ArrayList<Categories> categories) {
this.categories = categories;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public int getStock() {
return stock;
}
public String getPicture() {
return picture;
}
public ArrayList<Categories> getCategories() {
return categories;
}
#Override
public String toString() {
return "Product{" +
"productName='" + name + '\'' +
", productPrice=" + price +
", productStock=" + stock +
", productPicture='" + picture + '\'' +
", categories=" + categories +
'}';
}
}
2 Class (Categories.java) to read the array
package models;
public class Categories {
private int id;
private String description;
public int getId() {
return id;
}
public String getDescription() {
return description;
}
public void setId(int id) {
this.id = id;
}
public void setDescription(String description) {
this.description = description;
}
public Categories(int id, String description) {
this.id = id;
this.description = description;
}
#Override
public String toString() {
return "Category{" + "id=" + id + ", description=" + description + '}';
}
}
And this is the main
package p3;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import models.Product;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
String fichero = "";
try (BufferedReader br = new BufferedReader(new FileReader("src/res/FitxersJSON/products.json"))) {
String linea;
while ((linea = br.readLine()) != null) {
fichero += linea;
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
Product productObject = gson.fromJson(fichero.toString(), Product.class);
System.out.println(productObject);
}
}
For some reason when I execute the main I get this error
Exception in thread "main" com.google.gson.JsonIOException: JSON document was not fully consumed.
at com.google.gson.Gson.assertFullConsumption(Gson.java:861)
at com.google.gson.Gson.fromJson(Gson.java:854)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.google.gson.Gson.fromJson(Gson.java:774)
at p3.Main.main(Main.java:42)
I have tried formating the JSON document but looks like everything is ok because I can clearly read it printing the "linea" value in each loop.
Thank you in advance.
[EDIT]
I solved the problem by adding "[" and "]" at the beginning and the end of the JSON file and also "," to all lines excepting the last one.
package p3;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import models.Categories;
import models.Product;
import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class Main {
public static void main(String[] args) {
ex2_readProducts();
ex3_addProducts();
}
private static void ex2_readProducts() {
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Product>>() {
}.getType();
String file = "";
try (BufferedReader br = new BufferedReader(new FileReader("src/resources/products.json"))) {
String linea;
System.out.println("***************************** Reading the JSON file *********************************");
while ((linea = br.readLine()) != null) {
file += linea;
}
Collection<Product> enums = gson.fromJson(file, collectionType);
int counter = 0;
for (Product r : enums) {
counter++;
System.out.println("Product nº: " + counter );
System.out.println(r);
}
System.out.println("Result: " + counter + " products read from the file" );
System.out.println("***************************** Finished reading the JSON file *********************************");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static void ex3_addProducts() {
Gson gson = new Gson();
Categories c1 = new Categories(1, "tablet");
Categories c2 = new Categories(2, "game");
Categories c3 = new Categories(3, "phone");
Categories c4 = new Categories(5, "smartwatch");
Categories c5 = new Categories(9, " scooter");
Product p1 = new Product("ipad32", 1200, 23, "ipad32.jpg");
Product p2 = new Product("soccer 3000", 100, 500, "soccer.jpg");
Product p3 = new Product("pixel", 900, 900, "pixel.jpg");
Product p4 = new Product("mi watch", 300, 23, "miwatch.jpg");
Product p5 = new Product("mi scooter 365", 365, 23, "miscooter.jpg");
ArrayList<Categories> categoriesArrayList1;
categoriesArrayList1 = new ArrayList<>(Arrays.asList(c1, c3));
ArrayList<Categories> categoriesArrayList2;
categoriesArrayList2 = new ArrayList<>(Arrays.asList(c1, c2, c3));
ArrayList<Categories> categoriesArrayList3;
categoriesArrayList3 = new ArrayList<>(Arrays.asList(c1, c4, c3));
ArrayList<Categories> categoriesArrayList4;
categoriesArrayList4 = new ArrayList<>(Arrays.asList(c1, c3));
ArrayList<Categories> categoriesArrayList5;
categoriesArrayList5 = new ArrayList<>(Arrays.asList(c5, c1));
p1.setCategories(categoriesArrayList1);
p2.setCategories(categoriesArrayList2);
p3.setCategories(categoriesArrayList3);
p4.setCategories(categoriesArrayList4);
p5.setCategories(categoriesArrayList5);
Product[] productsArray = {p1, p2, p3, p4, p5};
try (BufferedWriter br = new BufferedWriter(new FileWriter("src/resources/products2.json"))) {
System.out.println("********************** Adding products to a new file: *********************************");
br.write("[");
br.newLine();
int counter = 0;
for (int i = 0; i < productsArray.length; i++) {
System.out.println("Product nº: " + (i+1) + '\n' + productsArray[i]);
String json = gson.toJson(productsArray[i]);
br.write(json);
if (i != productsArray.length - 1) {
br.write(",");
}
br.newLine();
counter = (i+1);
}
br.write("]");
System.out.println("Result: " + counter + " products added to the file" );
System.out.println("**************************** Finished adding products *****************************");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
First of all you are using Department instead of Categories in the java class. As I see it contains different fields. I believe your problem is inside the json file or Main class reading the file. Using Guava gives you easier reading files. See my code:
products.json
{
"name": "MacBook",
"price": 1299,
"stock": 10,
"picture": "macbook.jpeg",
"categories": [
{
"id": 1,
"name": "macbook"
},
{
"id": 2,
"name": "notebook"
}
]
}
Main.class
package com.test;
import com.google.common.io.Resources;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
Gson gson = new GsonBuilder()
.create();
String products = Resources.toString(Resources.getResource("products.json"), StandardCharsets.UTF_8).trim();
Product productObject = gson.fromJson(products, Product.class);
System.out.println(productObject);
}
}
output is
Product{name='MacBook', price=1299, stock=10, picture='macbook.jpeg', categories=[Category{id=1, name='macbook'}, Category{id=2, name='notebook'}]}
I think main problem that in json you have {"id": 1,"name": "macbook"} but in java class Categories you use private String description;, how json parser should understand that description and name are same field?
In my opioion, you should try to use name insted of description, for example
package models;
public class Categories {
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
...
}

Android: Use result from stringrequest in individual textviews

I have been able to get a string from an url, using volley. This string is now shown as one block in a textview. But I would like to be able to display this data in individual textviews. How could I do this?
Maybe important to know: I'm completely new at programming and this is my first week I'm doing this. So my method I used could be strange, and this might be a stupid question, but I'm just trying to learn, and to get the result I want.
This is the code I have now, to get the data from the url:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response.toString());
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
queue.add(request);
And this is how the result from the GET from the url looks like:
{"DeliveryDetailId":91003,"Delivery":{"DeliveryId":91,"DeliveryNumber":"1248","DropLocation":null,"DeliveryState":0},"ProductNumber":null,"Description":null,"PickLocation":"104","LocationCheck":null,"Quantity":64.0,"Histories":[],"BinNumberToUse":null}
So in this case I would like to have textviews which show the DeliveryID, Picklocation and Quantity. How can I extract this info from the string, so I can show it in the Textviews?
create model classes like below and store the response in Response.class
Then you can able to access DeliveryID by calling getDeliveryID()
-----------------------------------com.saranga.app.model.Delivery.java-----------------------------------
package com.saranga.app.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Delivery {
#SerializedName("DeliveryId")
#Expose
private Integer deliveryId;
#SerializedName("DeliveryNumber")
#Expose
private String deliveryNumber;
#SerializedName("DropLocation")
#Expose
private Object dropLocation;
#SerializedName("DeliveryState")
#Expose
private Integer deliveryState;
public Integer getDeliveryId() {
return deliveryId;
}
public void setDeliveryId(Integer deliveryId) {
this.deliveryId = deliveryId;
}
public String getDeliveryNumber() {
return deliveryNumber;
}
public void setDeliveryNumber(String deliveryNumber) {
this.deliveryNumber = deliveryNumber;
}
public Object getDropLocation() {
return dropLocation;
}
public void setDropLocation(Object dropLocation) {
this.dropLocation = dropLocation;
}
public Integer getDeliveryState() {
return deliveryState;
}
public void setDeliveryState(Integer deliveryState) {
this.deliveryState = deliveryState;
}
}
-----------------------------------com.saranga.app.model.Response.java-----------------------------------
package com.saranga.app.model;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response {
#SerializedName("DeliveryDetailId")
#Expose
private Integer deliveryDetailId;
#SerializedName("Delivery")
#Expose
private Delivery delivery;
#SerializedName("ProductNumber")
#Expose
private Object productNumber;
#SerializedName("Description")
#Expose
private Object description;
#SerializedName("PickLocation")
#Expose
private String pickLocation;
#SerializedName("LocationCheck")
#Expose
private Object locationCheck;
#SerializedName("Quantity")
#Expose
private Double quantity;
#SerializedName("Histories")
#Expose
private List<Object> histories = null;
#SerializedName("BinNumberToUse")
#Expose
private Object binNumberToUse;
public Integer getDeliveryDetailId() {
return deliveryDetailId;
}
public void setDeliveryDetailId(Integer deliveryDetailId) {
this.deliveryDetailId = deliveryDetailId;
}
public Delivery getDelivery() {
return delivery;
}
public void setDelivery(Delivery delivery) {
this.delivery = delivery;
}
public Object getProductNumber() {
return productNumber;
}
public void setProductNumber(Object productNumber) {
this.productNumber = productNumber;
}
public Object getDescription() {
return description;
}
public void setDescription(Object description) {
this.description = description;
}
public String getPickLocation() {
return pickLocation;
}
public void setPickLocation(String pickLocation) {
this.pickLocation = pickLocation;
}
public Object getLocationCheck() {
return locationCheck;
}
public void setLocationCheck(Object locationCheck) {
this.locationCheck = locationCheck;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public List<Object> getHistories() {
return histories;
}
public void setHistories(List<Object> histories) {
this.histories = histories;
}
public Object getBinNumberToUse() {
return binNumberToUse;
}
public void setBinNumberToUse(Object binNumberToUse) {
this.binNumberToUse = binNumberToUse;
}
}
You need to decode your JSONObject and individually get each element unless it's in a JSONArray in that case you need to loop through it
#Override
public void onResponse(String response) {
JSONObject json = new JSONObject(response);
textView.setText(json.getString("DeliveryDetailld"));
JSONObject details = json.getJSONObject("Delivery");
//Get data in Delivery Object
textView2.setText(details.getString("DeliveryId"));
}

How to call key inside another key with Json

I'm trying to pull one result into another, but I'm not sure how to do that. In case I have already been able to pull other results, but the one that is inside another key I can not.
I'm doing with Retrofit. I looked for some tutorials and video lessons, but I could not do it.
package com.example.apiunion.apiunion.models;
import java.util.ArrayList;
public class UltimosLancados {
private ArrayList<Lancamentos> dados;
public ArrayList<Lancamentos> getDados() {
return dados;
}
public void setDados(ArrayList<Lancamentos> dados) {
this.dados = dados;
}
}
public class Lancamentos implements Serializable {
private String titulo;
private String url;
private String capa;
private int id;
public String getCapa() {
return capa;
}
public void setCapa(String capa) {
this.capa = capa;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Parsing the JSON sample provided:
Android framework classes: JSONObject, JSONArray
package com.example.elletlar.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
private static final String TEST_STRING =
"{\"orden\":\"2018-7-199\"," +
"\"s\":\"2018-7-199\"," +
"\"capitulos\":{" +
"\"dados\":[" +
"{\"id\":\"169472\"," +
"\"capitulo\":\"75\"}, " +
"{\"id\":\"14952\"," +
"\"capitulo\":\"80\"}" +
"]" +
"}" +
"}";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
final JSONObject root = new JSONObject(TEST_STRING);
final String orden = root.getString("orden");
Log.i(TAG, orden);
final String s = root.getString("s");
Log.i(TAG, s);
final JSONObject capitulos = root.getJSONObject("capitulos");
final JSONArray dados = capitulos.getJSONArray("dados");
for (int i = 0; i < dados.length(); ++i) {
final JSONObject currentObj = dados.getJSONObject(i);
Log.i(TAG, currentObj.getString("capitulo"));
Log.i(TAG, currentObj.getString("id"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I've left the insertion of the values into the Lancamentos object Array to you. I'm sure that you know how to do that now that the JSON is fully parsed.

Java.net(RestFul service JSON reponse parsing issue) How to convert list of same item in JSON reponse String to Java Object?

I am calling Restful service using below code :(Java.net implementation )
StringBuilder responseStrBuilder = new StringBuilder();
try
{
URL url = new URL(restUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(httpRequestMethod);
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Content-Type", "application/json");
if (requestHeaders != null)
{
for (Map.Entry<String, String> entry : requestHeaders.entrySet())
{
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(urlParameters.getBytes());
os.flush();
os.close();
if (conn.getResponseCode() != 200) {//do something}
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
while ((output = br.readLine()) != null)
responseStrBuilder.append(output);
Approach 1:
I have below string(JSON String) as my Restful service response , how can I convert it to Java object. Since same(Itm) object is repeated multiple times if I use org.codehaus.jettison.json.JSONObject myObject = new org.codehaus.jettison.json.JSONObject(responseStrBuilder.toString());
It only reads first Itm Object and does not bring list of all item object.
JSON String output from service :
{"Response":{"RID":"04'34'",
"Itm":{"id":{"ab":"1","cd":"12"},"qw":"JK","name":"abcd "},
"Itm":{"id":{"ab":"2","cd":"34},"qw":"JK","name":"asdf "},
"Itm":{"id":{"ab":"3","cd":"12"},"qw":"JK","name":"fghj "}
}}
Approach 2:
I also tried below snippet with correct Java object with setters and getters
ObjectMapper objectMapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyJavaReponseObject javaObj = mapper.readValue(json, MyJavaReponseObject.class);
This approach also reads only one object of Itm and not all the object as its not coming in array format in JSON string. Is there any better way of getting all the object(Itm) mapped to single List of Object in java pojo ?
You can use the List class in your response object, if you should parse that json string itself.
I have a ReponseJSON class with json objects, one Response and three Itms
static class ReponseJSON {
private Response Response;
#JsonProperty("Response")
public Response getResponse() {
return Response;
}
public void setResponse(Response Response) {
this.Response = Response;
}
static class Response {
private String rid;
private Itm Itm;
private List<Itm> listItm = new ArrayList<Itm>();
public Itm getItm() {
return Itm;
}
#JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
public String getRID() {
return rid;
}
public List<Itm> getItms() {
return listItm;
}
#JsonProperty("RID")
public void setRID(String rid) {
this.rid = rid;
}
static class Itm {
private Id id;
private String qw, name;
public String getQw() {
return qw;
}
public void setQw(String qw) {
this.qw = qw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Id getId() {
return id;
}
public void setId(Id id) {
this.id = id;
}
static class Id {
private String ab, cd;
public String getCd() {
return cd;
}
public void setCd(String cd) {
this.cd = cd;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
}
}
}
}
In a Response class, I have a list class and save a Itm object whenever object mapper call this class.
static class Response {
... skip ..
private List<Itm> listItm = new ArrayList<Itm>();
... skip ..
#JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
}
Check the full source code as follows.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonParserTest {
static class ReponseJSON {
private Response Response;
#JsonProperty("Response")
public Response getResponse() {
return Response;
}
public void setResponse(Response Response) {
this.Response = Response;
}
static class Response {
private String rid;
private Itm Itm;
private List<Itm> listItm = new ArrayList<Itm>();
public Itm getItm() {
return Itm;
}
#JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
public String getRID() {
return rid;
}
public List<Itm> getItms() {
return listItm;
}
#JsonProperty("RID")
public void setRID(String rid) {
this.rid = rid;
}
static class Itm {
private Id id;
private String qw, name;
public String getQw() {
return qw;
}
public void setQw(String qw) {
this.qw = qw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Id getId() {
return id;
}
public void setId(Id id) {
this.id = id;
}
static class Id {
private String ab, cd;
public String getCd() {
return cd;
}
public void setCd(String cd) {
this.cd = cd;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
}
}
}
}
public static void main(String[] args) {
String responseJson =
"{\"Response\":{\"RID\":\"04'34'\","
+ "\"Itm\":{\"id\":{\"ab\":\"1\",\"cd\":\"12\"},\"qw\":\"JK\",\"name\":\"abcd\"}"
+ ",\"Itm\":{\"id\":{\"ab\":\"2\",\"cd\":\"34\"},\"qw\":\"JK\",\"name\":\"asdf\"}"
+ ",\"Itm\":{\"id\":{\"ab\":\"3\",\"cd\":\"12\"},\"qw\":\"JK\",\"name\":\"fghj\"}"
+ "}} ";
ObjectMapper mapper = new ObjectMapper();
ReponseJSON responseObj = null;
try {
responseObj = mapper.readValue(responseJson, ReponseJSON.class);
ReponseJSON.Response response = responseObj.getResponse();
for(int i = 0; i < response.getItms().size(); i++)
{
ReponseJSON.Response.Itm item = response.getItms().get(i);
System.out.println(item.getId().getAb());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The version of my jackson mapper is 2.9.1.
You check the main method of the source, because the JSON string you prepared is invalid as coddemonkey mentioned.
Have a good day.
Make your json response looks something similar to this
{"Response":{"RID":"04'34'",
"Itms":[{"id":{"ab":"1","cd":"12"},"qw":"JK","name":"abcd "},
{"id":{"ab":"2","cd":"34"},"qw":"JK","name":"asdf "},
{"id":{"ab":"3","cd":"12"},"qw":"JK","name":"fghj "}]
}}
then, use org.json jar to parse the string to jsonObject
JSONObject jsonObject=new JSONObject(responseString);
This is one type of solution, if you can't change the response as mentioned above then you have to manually parse the string(using java bean) there is no other option available.

Android Dynamic response type Retroft

hello i have Json response like this
[
{
"question": "hhhhh",
"question_answer": "hhhh ",
"question_type": "question type",
"questioner_age": "questioner age",
"questioner_city": "questioner city",
"questioner_country": "questioner country",
"questioner_name": "questioner name",
"questioner_sex": "questioner sex",
"comments_allowed": "1",
"question_id": "63",
"question_date": "05/08/2017 - 19:33",
"is_public": "1"
},
{
"question": "hhhh !!",
"question_answer": "hhhh",
"question_type": [],
"questioner_age": [],
"questioner_city": [],
"questioner_country": [],
"questioner_name": "hhhhh",
"questioner_sex": [],
"comments_allowed": "1",
"question_id": "57",
"question_date": "04/30/2017 - 14:24",
"is_public": "1"
}
]
if the column is null will return as an array like this "question_type": [],
if not will return as a string !
so i tried to get this response on retrofit but i failed and always got this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 4 column 2 path $
after i searched in the internet i tried something like this but its not working !!
Gson gson = new Gson();
String json = response.body().toString();
if (json instanceof String)
{
MyQuestionModelString parseObject = gson.fromJson(json, MyQuestionModelString.class);
apiCallResponse.onSuccess(parseObject,responseMessage);
}else {
MyQuestionModel parseObject = gson.fromJson(json, MyQuestionModel.class);
apiCallResponse.onSuccess(parseObject,responseMessage);
}
any help !
UPDATAE !
this is my model for this response and same error !!!
public class MyQuestionModel {
#SerializedName("question")
#Expose
private String question;
#SerializedName("question_answer")
#Expose
private String questionAnswer;
#SerializedName("question_type")
#Expose
private List<Object> questionType = null;
#SerializedName("questioner_age")
#Expose
private List<Object> questionerAge = null;
#SerializedName("questioner_city")
#Expose
private List<Object> questionerCity = null;
#SerializedName("questioner_country")
#Expose
private List<Object> questionerCountry = null;
#SerializedName("questioner_name")
#Expose
private String questionerName;
#SerializedName("questioner_sex")
#Expose
private List<Object> questionerSex = null;
#SerializedName("comments_allowed")
#Expose
private String commentsAllowed;
#SerializedName("question_id")
#Expose
private String questionId;
#SerializedName("question_date")
#Expose
private String questionDate;
#SerializedName("is_public")
#Expose
private String isPublic;
}
My Main issue that how to define this field ! question_type
screen shot
During the parsing of json if the SerializedName key is not found it will throw an exception. Use #Expose to let the deserializer to know that this field can be null. Here is a similar Model of your mentioned response
public class ResponsePojo {
List<Data> data;
public class Data {
#Expose
#SerializedName("question")
String question;
#Expose
#SerializedName("question_answer")
String questionAnswer;
#Expose
#SerializedName("question_type")
String questionType;
#Expose
#SerializedName("questioner_age")
String questionerAge;
#Expose
#SerializedName("questioner_city")
String questionerCity;
#Expose
#SerializedName("questioner_country")
String questionerCountry;
#Expose
#SerializedName("questioner_name")
String questionerName;
#Expose
#SerializedName("questioner_sex")
String questionerSex;
#Expose
#SerializedName("comments_allowed")
String commentsAllowed;
#Expose
#SerializedName("question_id")
String questionId;
#Expose
#SerializedName("question_date")
String questionDate;
#Expose
#SerializedName("is_public")
String isPublic;
}
}
You must indicate which paramters or objects in the model are optional with #Exposed tag.
Example
#Expose
#SerializedName("question_type")
private String mQuestionType;
You problem is
ava.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 4 column 2 path $
If your json code is [...],your return is JSONArray , you can use Gsonto parse it to List<Object> .
If your json code is {...},your return is JSONObject , you can use Gsonto parse it to Object .
So you should use List<MyQuestionModel> to get parsed data .
Change MyQuestionModel to List<MyQuestionModel> in your call code .
Sample
Call<List<MyQuestionModel>> getData();
And my code for doing it .
JSONEntity for you json
public class JSONEntity {
/**
* question : hhhhh
* question_answer : hhhh
* question_type : question type
* questioner_age : questioner age
* questioner_city : questioner city
* questioner_country : questioner country
* questioner_name : questioner name
* questioner_sex : questioner sex
* comments_allowed : 1
* question_id : 63
* question_date : 05/08/2017 - 19:33
* is_public : 1
*/
private String question;
private String question_answer;
private String question_type;
private String questioner_age;
private String questioner_city;
private String questioner_country;
private String questioner_name;
private String questioner_sex;
private String comments_allowed;
private String question_id;
private String question_date;
private String is_public;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getQuestion_answer() {
return question_answer;
}
public void setQuestion_answer(String question_answer) {
this.question_answer = question_answer;
}
public String getQuestion_type() {
return question_type;
}
public void setQuestion_type(String question_type) {
this.question_type = question_type;
}
public String getQuestioner_age() {
return questioner_age;
}
public void setQuestioner_age(String questioner_age) {
this.questioner_age = questioner_age;
}
public String getQuestioner_city() {
return questioner_city;
}
public void setQuestioner_city(String questioner_city) {
this.questioner_city = questioner_city;
}
public String getQuestioner_country() {
return questioner_country;
}
public void setQuestioner_country(String questioner_country) {
this.questioner_country = questioner_country;
}
public String getQuestioner_name() {
return questioner_name;
}
public void setQuestioner_name(String questioner_name) {
this.questioner_name = questioner_name;
}
public String getQuestioner_sex() {
return questioner_sex;
}
public void setQuestioner_sex(String questioner_sex) {
this.questioner_sex = questioner_sex;
}
public String getComments_allowed() {
return comments_allowed;
}
public void setComments_allowed(String comments_allowed) {
this.comments_allowed = comments_allowed;
}
public String getQuestion_id() {
return question_id;
}
public void setQuestion_id(String question_id) {
this.question_id = question_id;
}
public String getQuestion_date() {
return question_date;
}
public void setQuestion_date(String question_date) {
this.question_date = question_date;
}
public String getIs_public() {
return is_public;
}
public void setIs_public(String is_public) {
this.is_public = is_public;
}
}
And the code for parse it .
Gson gson = new Gson();
String jsonString = response.body().string();
Type type = new TypeToken<List<JSONEntity>>() {
}.getType();
List<JSONEntity> datas = gson.fromJson(jsonString, type);
EDIT
If your response is JSONArray , you can try like this .
List<JSONEntity> datas = response.body();
Try to change your JSON Structure
First Approach
To
If the column is null return "question_type": null,else show "question_type": "value"
Instead
If the column is null will return as an array like this "question_type": [], if not will return as a string!
Second Approach Without changing Json structure
Handling Dynamic JSON Using Gson
Try this:
You have to use deserialize to parse dynamic datatype in json
In the reponse pojo use object
Ex:
Call<Object> call = //your API call ResponsePojo instead use `Object`
call.enqueue(new Callback<Object>()
{
#Override
public void onResponse(Response<Object> response, Retrofit retrofit)
{
try {
JSONArray jsonArray=new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(ServerResponse.class, new ServerResponse.OptionsDeserilizer())
.create();
ServerResponse serverResponse=gson.fromJson(jsonArray.get(i).toString(), ServerResponse.class);
System.out.println(serverResponse);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t)
{
///Handle failure
}
});
Use this ServerResponsePojo with JsonDeserializer
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class ServerResponse {
#SerializedName("question")
#Expose
private String question;
#SerializedName("question_answer")
#Expose
private String questionAnswer;
private String questionerName;
#SerializedName("comments_allowed")
#Expose
private String commentsAllowed;
#SerializedName("question_id")
#Expose
private String questionId;
#SerializedName("question_date")
#Expose
private String questionDate;
#SerializedName("is_public")
#Expose
private String isPublic;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getQuestionAnswer() {
return questionAnswer;
}
public void setQuestionAnswer(String questionAnswer) {
this.questionAnswer = questionAnswer;
}
/* public List<OptionValue> getQuestionerAge() {
return questionerAge;
}
public void setQuestionerAge(List<OptionValue> questionerAge) {
this.questionerAge = questionerAge;
}
public List<OptionValue> getQuestionerCity() {
return questionerCity;
}
public void setQuestionerCity(List<OptionValue> questionerCity) {
this.questionerCity = questionerCity;
}
public List<OptionValue> getQuestionerCountry() {
return questionerCountry;
}
public void setQuestionerCountry(List<OptionValue> questionerCountry) {
this.questionerCountry = questionerCountry;
}
*/
public String getQuestionerName() {
return questionerName;
}
public void setQuestionerName(String questionerName) {
this.questionerName = questionerName;
}
/*
public List<OptionValue> getQuestionerSex() {
return questionerSex;
}
public void setQuestionerSex(List<OptionValue> questionerSex) {
this.questionerSex = questionerSex;
}*/
public String getCommentsAllowed() {
return commentsAllowed;
}
public void setCommentsAllowed(String commentsAllowed) {
this.commentsAllowed = commentsAllowed;
}
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public String getQuestionDate() {
return questionDate;
}
public void setQuestionDate(String questionDate) {
this.questionDate = questionDate;
}
public String getIsPublic() {
return isPublic;
}
public void setIsPublic(String isPublic) {
this.isPublic = isPublic;
}
public class OptionValue {
}
public void setQuestionType(String questionType) {
this.questionType = questionType;
}
String questionType;
public static class OptionsDeserilizer implements JsonDeserializer<ServerResponse> {
#Override
public ServerResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Type listType = new TypeToken<ServerResponse>() {
}.getType();
ServerResponse options = (ServerResponse) new Gson().fromJson(json, listType);
JsonObject jsonArrayValue = json.getAsJsonObject();
for (int i = 0; i < jsonArrayValue.size(); i++) {
JsonObject jsonObject = jsonArrayValue.getAsJsonObject();
if (jsonObject.has("question_type")) {
JsonElement elem = (JsonElement) jsonObject.get("question_type");
if (elem != null && !elem.isJsonNull() && !elem.isJsonArray()) {
String valuesString = elem.getAsString();
if (!TextUtils.isEmpty(valuesString)) {
options.setQuestionType(valuesString);
} else {
options.setQuestionType("");
}
//Do your other stuffs
}
}
}
return options;
}
}
}
This is working happy codeing

Categories

Resources