Convert JSON array to Java Class Object List - java

I have a JSON string that comes from a WFC service. When I try to convert JSON array into List object, I've got the following error :
".JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: java.io.StringReader#41f27f18; line: 1, column: 1]"
The Java class (Card Class):
public class Card {
public String ID;
public String CompanyID;
public String CompanyName;
public String FiscalCode;
public String Limit;
public String StateID;
public String CardState;
public String Deleted;
public String Sold;
public String StartDate;
public String InvoiceStartDate;
public String Quantity;
public String Value;
public String CardTypeID;
public String CardType;
public String SoldChanged;
public String DriverName;
public String VehiclePlateNumber;
public String VehicleID;
public String Discount;
public String ContractID;
public String DiscountPerMonth;
public String ProductID;
public String ProductStateID;
public String Mail;
public String WithoutLimit;
public String ContractSold;
public String ContractLimit;
public String NumberOfTransactions;
public String DriverNameOnly;
public String DriverSurnameOnly;
}
The Java code to deserialize :
strResponse = responseHandler.handleResponse(response);
if (strResponse.contains("Credit") || strResponse.contains("Debit")) {
ObjectMapper mapper = new ObjectMapper();
strResponse= strResponse.replace("\"GetCardsResult\":", "");
userCards = mapper.readValue(strResponse, mapper.getTypeFactory().constructCollectionType(List.class, Card.class));
}
The JSON string:
{ "GetCardsResult":"[{\"ID\":3,\"CompanyID\":1155,\"CompanyName\":\"test\",\"FiscalCode\":null,\"Code\":\"1423127205\",\"Limit\":0.000,\"StateID\":1,\"CardState\":\"Activ\",\"Deleted\":false,\"Sold\":0.000,\"StartDate\":\"\/Date(1412974800000+0300)\/\",\"InvoiceStartDate\":\"\/Date(-62135596800000+0200)\/\",\"Quantity\":null,\"Value\":0.0,\"CardTypeID\":1,\"CardType\":\"Credit\",\"SoldChanged\":false,\"DriverName\":\"\",\"VehiclePlateNumber\":\"B 222 ART\",\"VehicleID\":null,\"Discount\":null,\"ContractID\":15,\"DiscountPerMonth\":null,\"ProductID\":null,\"ProductStateID\":null,\"Mail\":\"\",\"WithoutLimit\":true,\"ContractSold\":null,\"ContractLimit\":null,\"NumberOfTransactions\":null,\"DriverNameOnly\":null,\"DriverSurnameOnly\":null},{\"ID\":2881,\"CompanyID\":1155,\"CompanyName\":\"test\",\"FiscalCode\":null,\"Code\":\"test0000\",\"Limit\":125.000,\"StateID\":1,\"CardState\":\"Activ\",\"Deleted\":false,\"Sold\":132.330,\"StartDate\":\"\/Date(1436130000000+0300)\/\",\"InvoiceStartDate\":\"\/Date(-62135596800000+0200)\/\",\"Quantity\":null,\"Value\":0.0,\"CardTypeID\":1,\"CardType\":\"Credit\",\"SoldChanged\":false,\"DriverName\":\"aaa aaa\",\"VehiclePlateNumber\":\"aaa\",\"VehicleID\":null,\"Discount\":null,\"ContractID\":15,\"DiscountPerMonth\":null,\"ProductID\":null,\"ProductStateID\":null,\"Mail\":\"\",\"WithoutLimit\":true,\"ContractSold\":null,\"ContractLimit\":null,\"NumberOfTransactions\":null,\"DriverNameOnly\":null,\"DriverSurnameOnly\":null}]" }
Thanks in advance!

Try this:
try {
JSONObject jsonObject = null;
yourJSONString.replace("\\", "");
jsonObject = new JSONObject(yourJSONString);
String newJSONString = jsonObject.get("GetCardsResult").toString();
JSONArray jsonMainArr = new JSONArray(newJSONString);
//now just loop the json Array
for (int i = 0; i < jsonMainArr.length(); ++i) {
JSONObject rec = jsonMainArr.getJSONObject(i);
card.set_id(rec.get("ID").toString());
//....
}
} catch (JSONException e) {
e.printStackTrace();
}

Try to use GSON its very efficient and easy to implement, As example below will be your POJO class.
public class Post {
#SerializedName("id")
public long ID;
public String title;
public String author;
public String url;
#SerializedName("date")
public Date dateCreated;
public String body;
public List tags;
public Post() {
}
}
//Tag.java
public class Tag {
public String name;
public String url;
public Tag() {
}
}
And this will how you parse your JSON string to Object Class,
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Post> posts = new ArrayList<Post>();
posts = Arrays.asList(gson.fromJson(reader, Post[].class));
content.close();

What do you pass to the mapper - string before or after compiling the regular expression?
Did you try any external lib like Gson? Everything you need is just new Gson().fromJson(strResponse, new TypeToken<List<Card>>() {}.getType(););

Related

How can I parse object inside array using retrofit

[
{
"login": "mojombo",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mojombo",
"html_url": "https://github.com/mojombo",
"followers_url": "https://api.github.com/users/mojombo/followers",
"following_url": "https://api.github.com/users/mojombo/following{/other_user}",
"gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
"organizations_url": "https://api.github.com/users/mojombo/orgs",
"repos_url": "https://api.github.com/users/mojombo/repos",
"events_url": "https://api.github.com/users/mojombo/events{/privacy}",
"received_events_url": "https://api.github.com/users/mojombo/received_events",
"type": "User",
"site_admin": false
}
]
Json: https://api.github.com/users
This is URL of an API... how can i parse this object to fetch the data using retrofit?
Here is the example on how to fetch JSON object with array using retrofit. I believe you won't have troubles changing it to work with your data.
Example.java
public class Example {
#SerializedName("PnrNumber")
#Expose
private String pnrNumber;
#SerializedName("Status")
#Expose
private String status;
#SerializedName("ResponseCode")
#Expose
private String responseCode;
#SerializedName("TrainNumber")
#Expose
private String trainNumber;
#SerializedName("TrainName")
#Expose
private String trainName;
#SerializedName("JourneyClass")
#Expose
private String journeyClass;
#SerializedName("ChatPrepared")
#Expose
private String chatPrepared;
#SerializedName("From")
#Expose
private String from;
#SerializedName("To")
#Expose
private String to;
#SerializedName("JourneyDate")
#Expose
private String journeyDate;
#SerializedName("Passangers")
#Expose
private List<Passanger> passangers = null;
public String getPnrNumber() {
return pnrNumber;
}
public void setPnrNumber(String pnrNumber) {
this.pnrNumber = pnrNumber;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResponseCode() {
return responseCode;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
public String getTrainNumber() {
return trainNumber;
}
public void setTrainNumber(String trainNumber) {
this.trainNumber = trainNumber;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getJourneyClass() {
return journeyClass;
}
public void setJourneyClass(String journeyClass) {
this.journeyClass = journeyClass;
}
public String getChatPrepared() {
return chatPrepared;
}
public void setChatPrepared(String chatPrepared) {
this.chatPrepared = chatPrepared;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getJourneyDate() {
return journeyDate;
}
public void setJourneyDate(String journeyDate) {
this.journeyDate = journeyDate;
}
public List<Passanger> getPassangers() {
return passangers;
}
public void setPassangers(List<Passanger> passangers) {
this.passangers = passangers;
}
}
Passanger.Java
public class Passanger {
#SerializedName("Passenger")
#Expose
private String passenger;
#SerializedName("BookingStatus")
#Expose
private String bookingStatus;
#SerializedName("CurrentStatus")
#Expose
private String currentStatus;
public String getPassenger() {
return passenger;
}
public void setPassenger(String passenger) {
this.passenger = passenger;
}
public String getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(String bookingStatus) {
this.bookingStatus = bookingStatus;
}
public String getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
}
}
Here are the classes which are generated from the Response which you have provided in the question.
You can use this link to generate the POJO class for JSON response.
JSON TO POJO
Add this gradle:
implementation 'com.google.code.gson:gson:2.8.2'
Init the Gson buildr:
private Gson gson;
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
gson = gsonBuilder.create();
Parse the JSON using GSON
gson.fromJson(jsonObject.getJSONObject("data").toString(), Example.class);
These are the basic steps to parse the JSON using GSON.
For more information you can refer to the below article:
Parsing JSON on Android using GSON
Or Check the GSON official GitHub Repository
GSON

Null Pointer Exception while trying to use GSON API for json reading

Lines of Code:
//Error LINE:
Step trying to read data using method from JsonDataReader Class(Code follows next)
public void enter_personal_details_on_checkout_page(String customerFirstName) throws InterruptedException{
Customer customer=FileReaderManager.getInstance().getJsonDataReader().getCustomerByFirstName(customerFirstName);
checkoutPage.fill_PersonalDetails(customer);
}
JSON Data Reader Class:
public class JsonDataReader {
private final String customerFilePath = FileReaderManager.getInstance().getConfigReader().getTestDataResourcePath() + "Customer.json";
private List<Customer> customerList;
public JsonDataReader(){
customerList = getCustomerData();
}
private List<Customer> getCustomerData() {
Gson gson = new Gson();
BufferedReader bufferReader = null;
try {
bufferReader = new BufferedReader(new FileReader(customerFilePath));
Customer[] Customer = gson.fromJson(bufferReader, Customer[].class);
return Arrays.asList(Customer);
}catch(FileNotFoundException e) {
throw new RuntimeException("Json file not found at path : " + customerFilePath);
}finally {
try { if(bufferReader != null) bufferReader.close();}
catch (IOException ignore) {}
}
}
My JSON POJO Class:
public class Customer {
public String firstName;
public String lastName;
public Integer age;
public String emailAddress;
public Address address;
public PhoneNumber phoneNumber;
public class Address {
public String streetAddress;
public String city;
public String postCode;
public String state;
public String country;
public String county;
}
public class PhoneNumber {
public String home;
public String mob;
}
}
Used below steps trying to read the JSON reader:
JSON Data set
Java POJO class to represent JSON data
A JSON Data Reader class
==> Can anyone tell how can i resolve this issue of 'NullPointerException' here?

Java convert Java object to Json object

I can not convert Java object to JSON object this is my main java object :
I do this:
public class LoginDao {
String company;
String user;
String secure_password;
String secure_device_id;
app_info app_info;
}
jsonObject.put("company", company);
jsonObject.put("user", user);
jsonObject.put("os", os);
jsonObject.put("ver", ver);
jsonObject.put("lang", lang);
but on output I do not have this :
{
"company":"",
"user":"test",
"secure_password":"",
"secure_device_id":"",
"app_info":
{
"os":"soapui",
"ver":1,
"lang":"pl"
}
}
You can do this in many more way. Here are given bellow:
Using Google Gson:
Maven dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
Java code:
LoginDao loginData;
// Here loginData is the object. ...
Gson gson = new Gson();
String json = gson.toJson(loginData);
Using Jackson:
Gradle Dependency:
compile 'com.fasterxml.jackson.core:jackson-databind:2.5.3'
Java code
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(loginData);
If you need above output, try this:
JSONObject obj = new JSONObject();
obj.put("company", company);
obj.put("user", user);
obj.put("secure_password", secure_password);
obj.put("secure_device_id", secure_device_id);
JSONObject anothetObj = new JSONObject();
anothetObj.put("os", os);
anothetObj.put("ver", ver);
anothetObj.put("lang", lang);
obj.put("app_info", anothetObj);
You can create two DAO Classes,
public class LoginDAO {
private String company;
private String user;
private String secure_password;
private String secure_device_id;
// Getter Methods
public String getCompany() {
return company;
}
public String getUser() {
return user;
}
public String getSecure_password() {
return secure_password;
}
public String getSecure_device_id() {
return secure_device_id;
}
// Setter Methods
public void setCompany( String company ) {
this.company = company;
}
public void setUser( String user ) {
this.user = user;
}
public void setSecure_password( String secure_password ) {
this.secure_password = secure_password;
}
public void setSecure_device_id( String secure_device_id ) {
this.secure_device_id = secure_device_id;
}
}
public class App_info {
private String os;
private float ver;
private String lang;
// Getter Methods
public String getOs() {
return os;
}
public float getVer() {
return ver;
}
public String getLang() {
return lang;
}
// Setter Methods
public void setOs( String os ) {
this.os = os;
}
public void setVer( float ver ) {
this.ver = ver;
}
public void setLang( String lang ) {
this.lang = lang;
}
}
An then you can do this,
LoginDAO login = new LoginDAO();
App_info app = new App_info();
JSONObject jo = new JSONObject();
jo.put("company", login.getCompany());
jo.put("user", login.getUser());
jo.put("secure_password", login.getSecure_password());
jo.put("secure_device_id", login.getSecure_device_id());
Map m = new LinkedHashMap(3);
m.put("os", app.getOs());
m.put("ver", app.getVer());
m.put("lang", app.getLang());
jo.put("app_info", m);
System.out.println(jo.toString);
If not you can simply do this,
JSONObject jo = new JSONObject(
"{ \"company\":\"\", \"user\":\"test\", \"secure_password\":\"\", \"secure_device_id\":\"\", \"app_info\": { \"os\":\"soapui\", \"ver\":1, \"lang\":\"pl\" } }"
);

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

LibGDX parsing standard json to an object

I have a very basic problem.
I read though the LibGDX documentation a few times regarding JSON and Google around for an answer but it still does't work..
Basically I'm pulling json from a server like such which works as:
{"id":1,"facebook_id":"23432232","json":"{\"json\":\"test\"}"}
I have a class like this:
public class ServerJson
{
public static final String NAME = "ServerJson";
private int id;
private String facebookID;
private String json;
public ServerJson(){}
public ServerJson(int id, String facebookID, String json)
{
this.id = id;
this.facebookID = facebookID;
this.json = json;
}
public int getId() {
return id;
}
public String getFacebookID() {
return facebookID;
}
public String getJson() {
return json;
}
When I try to parse the code, it doesn't work. I get null:
String resultString = httpResponse.getResultAsString(); //{"id":1,"facebook_id":"23432232","json":"{\"json\":\"test\"}"}
Json json = new Json();
ServerJson serverJson = json.fromJson(ServerJson.class, resultString);
log(serverJson.getFacebookID()); //<< Is null.
Make sure the fields of your object class match up with the fields of the json object.

Categories

Resources