I am trying to implement deserialization to parse json object as a string, but my custom deserializable class is not being called.
JSON which needs to be parsed
{
"status": true,
"student": [
{
"id": 1,
"name": "",
"age": "",
"title": "",
}
]
}
My Deserializable class
public class MyDeserializer implements JsonDeserializer<StudentData> {
#Override
public StudentData deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) {
try {
String content = je.getAsJsonObject().get("student").getAsString();
return new Gson().fromJson(content, StudentData)
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Register my deserializer:-
MyDeserializer myDeserializer = new MyDeserializer();
Gson gson = new GsonBuilder().registerTypeAdapter(NotificationResponse.class, myDeserializer).create();
mRestAdapter = new RestAdapter.Builder().setServer(baseUrl).setConverter(new GsonConverter(gson)).setLogLevel(RestAdapter.LogLevel.FULL).setRequestInterceptor(new RequestInterceptor()
{
#Override
public void intercept(RequestFacade requestFacade) {
}
}).build();
I think this tutorial will help you implement a Deserializer(and might introduce some new concepts)
Try it, and see if it work for you!
For something that simple I don't think adding Gson as a dependency is worth it.
Example:
JSONObject jObj = new JSONObject(theJsonYouPostedAbove);
boolean status = jObj.getBoolean("status");
JSONArray jArr = jObj.getJSONArray("student");
for (int i = 0; i < jArr.length(); i++) {
JSONObject jo = jArr.getJSONObject(i);
int id = jo.getInt("id");
String name = jo.getString("name");
...
}
Related
I am trying to parse json result without array name. Here is my json response:
[
{
"Id": 2293,
"Name": "Dr.",
"Active": true
},
{
"Id": 2305,
"Name": "Mr.",
"Active": true
},
{
"Id": 2315,
"Name": "Mrs.",
"Active": true
}
]
How to parse this using com.squareup.retrofit2:retrofit:2.1.0 library?
Create One Class Like,
class Test {
public List<TestValue> testValues;
}
Then call API,
Call<List<Test>> getTestData(#Field("xyz") String field1);
Call <List<Test>> call = service.getTestData("val");
call.enqueue(new Callback<List<Test>>() {
#Override
public void onResponse(Call<List<Test>> call, Response<List<Test>>
response) {
List<Test> rs = response.body();
}
#Override
public void onFailure(Call<List<Test>> call, Throwable t) {
}
});
User Your Model class, this is only for example purpose.
Normally you can parse as
String response = "[{"Id": 2293,"Name": "Dr.","Active": true},{"Id": 2305,"Name": "Mr.","Active": true},{"Id": 2315,"Name": "Mrs.","Active": true}]";
try {
JSONArray ja = new JSONArray(response);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
String id = jo.getString("Id");
String name = jo.getString("Name");
String active = jo.getString("Active");
}
} catch (JSONException e) {
e.printStackTrace();
}
If you want to parse it using Model Class then your Model Class will be for Retrofit
class Response
{
#SerializedName("Id")
#Expose
private String id;
#SerializedName("Name")
#Expose
private String name;
#SerializedName("Active")
#Expose
private String active;
}
and define Callback for retrofit like that
Call<List<Meeting>> getMeetings(#Field String data );
Hope this will help
This question already has answers here:
Parsing JSON object in android
(5 answers)
Closed 4 years ago.
I am trying to parse the following API data. I just have to use the start time, end time, location and event name inside my app. I have never parse this type of data before. Hitting the API URL and getting a response is working fine, I just need help in parsing.
I have tried these solutions but it didn't work.
parsing JSON 2 arrays (embedded) in Android
How to Parsing JSON (Two Dimensional) array Object in android?
How to parse JsonArray and JSON Object having two keys and values in android?
Ask Android parsing JSON multiple arrays.
JSON:
[
{
"end": {
"endDate": "2018-03-09",
"endTime": "03:00",
"_id": "5a901a7d9fee7d156d594b04"
},
"location": "Dance Tent",
"start": {
"startDate": "2018-03-09",
"startTime": "02:00",
"_id": "5a901a7d9fee7d156d594b05"
},
"announcementName": "Jumanji Dance Party"
}
]
Code:
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
String fullName = jsonObject.getString("startTime");
String about = jsonObject.getString("announcementName");
String artistType = jsonObject.getString("endTime");
String link = jsonObject.getString("location");
//String avatar = jsonObject.getString("avatar");
Annoucement_Day_One artistInfoGetter=new Annoucement_Day_One( fullName,about, artistType, link );
annoucementDayOneList.add(artistInfoGetter);
wednesdayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("ERRROR RES: ", error.toString());
myInstance.dismiss();
}
});
requestQueue.add(jsonArrayRequest);
Try this
try {
JSONArray jsonArray= new JSONArray(response);
for (int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String location=object.getString("location");
String announcementName=object.getString("announcementName");
JSONObject end=object.getJSONObject("end");
String endDate=end.getString("endDate");
String endTime=end.getString("endTime");
String id=end.getString("_id");
JSONObject start=object.getJSONObject("start");
String startDate=start.getString("startDate");
String startTime=start.getString("startTime");
String start_id=start.getString("_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this ,
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
JSONObject startJson = jsonObject.getJSONObject("start");
String startTime = startJson.getString("startTime");
JSONObject endJson = jsonObject.getJSONObject("end");
String endTime = endJson.getString("endTime");
String announcementName = jsonObject.getString("announcementName");
String location = jsonObject.getString("location");
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayList<Holder1> arrayList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
for(int index = 0 ;index < jsonArray.length() ; index++){
JSONObject jsonObject1 = jsonArray.getJSONObject(index);
//make a holder for end, location, start,announcementName
Holder1 holder = new Holder1();
holder.setLocation(jsonObject1.optString("location"));
holder.setAnnouncementName(jsonObject1.optString("announcementName"));
//------------
JSONObject jsonObjectEnd =jsonObject1.getJSONObject("end");
holder.setEndDate(jsonObjectEnd.optString("endDate"));
holder.setEndTime(jsonObjectEnd.optString("endTime"));
holder.setEndID(jsonObjectEnd.optString("_id"));
//--------------
JSONObject jsonObjectStart =jsonObject1.getJSONObject("start");
holder.setStartDate(jsonObjectStart.optString("startDate"));
holder.setStartTime(jsonObjectStart.optString("startTime"));
holder.setStartID(jsonObjectStart.optString("_id"));
//--------------
arrayList.add(holder);
}
} catch (JSONException e) {
e.printStackTrace();
}
Accept the answer. If you like the way i have written.
You can use the GSON library by google.
add the dependency in build.gradle.
compile 'com.google.code.gson:gson:2.8.0'
First, you have to create the model class for your JSON response. this will help you to create the model class.
public class MyPojo
{
private Start start;
private String location;
private String announcementName;
private End end;
public Start getStart ()
{
return start;
}
public String getLocation ()
{
return location;
}
public String getAnnouncementName ()
{
return announcementName;
}
public End getEnd ()
{
return end;
}
}
--------------Start.Java------------
public class Start
{
private String startTime;
private String startDate;
private String _id;
public String getStartTime ()
{
return startTime;
}
public String getStartDate ()
{
return startDate;
}
public String get_id ()
{
return _id;
}
}
------------End.Java-------------------
public class End
{
private String _id;
private String endDate;
private String endTime;
public String get_id ()
{
return _id;
}
public String getEndDate ()
{
return endDate;
}
public String getEndTime ()
{
return endTime;
}
}
Now in your onResponse method
MyPojo respnse = new Gson().fromJson(response.toString(), MyPojo.class);
you can access any method from response.Ex. response.getEnd().getEnd_date()
I have a JSoN data like this:
{
"data": {
"noofCity": "1",
"City 1": [
{
"id": "12",
"title": "Delhi"
}
]
},
"success": true
}
Now based on noofCity next tag City 1 will be generated. If noofCity will be 2 then there are two tag City 1 and City 2. Then how can I parse it using Json? Please tell me how can I generate my POJO class structure.
Your POJOs should look like below:
Main POJO for Response:
public class Response {
Data data;
boolean success;
}
For Data
public class Data {
int noofCity;
Map<String, List<City>> cityMap;
void put(String key, List<City> city){
if(cityMap == null){
cityMap = new HashMap<>();
}
cityMap.put(key, city);
}
public void setNoofCity(int noofCity) {
this.noofCity = noofCity;
}
public int getNoofCity() {
return noofCity;
}
}
For City
public class City {
int id;
String title;
}
But one of the most important think is a way how to deserialise Data. You have to prepare your own deserialiser for this, and define way how to fill HashMap as is shown in the code below:
public class DataDeserializer implements JsonDeserializer<Data> {
#Override
public Data deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Data result = new Data();
Gson gson = new Gson();
JsonObject jsonObject= json.getAsJsonObject();
result.setNoofCity(jsonObject.get("noofCity").getAsInt());
for(int i =1; i<=result.getNoofCity() ; i++ ){
List<City> cities= gson.fromJson(jsonObject.getAsJsonArray("City "+ i), List.class);
result.put("City "+ i, cities);
}
return result;
}
}
And now you can deserialise you json
Gson gson = new GsonBuilder()
.registerTypeAdapter(Data.class, new DataDeserializer())
.create();
Response test = gson.fromJson(json, Response.class);
I have tree JSON-structured data.
Something like
{
"result": [
{
"id": 1,
"name": "test1"
},
{
"id": 2,
"name": "test12",
"children": [
{
"id": 3,
"name": "test123",
"children": [
{
"id": 4,
"name": "test123"
}
]
}
]
}
]
}
model:
class DataEntity {
int id;
String name;
List<DataEntity> childDataEntity;
}
Parsing via org.json
List<DataEntity> categories = new ArrayList<DataEntity>();
private List<DataEntity> recursivellyParse(DataEntity entity, JSONObject object) throws JSONException {
entity.setId(object.getInt("id"));
entity.setName(object.getString("name"));
if (object.has("children")) {
JSONArray children = object.getJSONArray("children");
for (int i = 0; i < children.length(); i++) {
entity.setChildDataEntity(recursivellyParse(new DataEntity(), children.getJSONObject(i)));
categories.add(entity);
}
}
return categories;
}
call
JSONObject jsonObject = new JSONObject(JSON);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
recursivellyParse(new DataEntity(), jsonArray.getJSONObject(i));
}
But this way is wrong. After execution of the method List filled out same data.
How do I parse it right?
UPD: update JSON.
Here is Full Demo How to Parse json data as you want.
String JSON = "your json string";
ArrayList<DataEntity> finalResult = new ArrayList<>();
try {
JSONObject main = new JSONObject(JSON);
JSONArray result = main.getJSONArray("result");
for(int i=0;i<result.length();i++){
DataEntity dataEntity = parseObject(result.getJSONObject(i));
finalResult.add(dataEntity);
}
Log.d("DONE","Done Success");
} catch (JSONException e) {
e.printStackTrace();
}
Create One recursive function to parse object.
public DataEntity parseObject(JSONObject dataEntityObject) throws JSONException {
DataEntity dataEntity = new DataEntity();
dataEntity.id = dataEntityObject.getString("id");
dataEntity.name = dataEntityObject.getString("name");
if(dataEntityObject.has("children")){
JSONArray array = dataEntityObject.getJSONArray("children");
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
DataEntity temp = parseObject(jsonObject);
dataEntity.children.add(temp);
}
}
return dataEntity;
}
Model Class
public class DataEntity implements Serializable {
public String id = "";
public String name = "";
ArrayList<DataEntity> children = new ArrayList<>();}
In FinalResult Arraylist you will get all your parse data.
Ignoring that the JSON you show is invalid (i'm going to assume that's a copy/paste problem or typo), the issue is that you've declared your categories List as a member of whatever object that is.
It's continually getting added to on every call to recursivellyParse() and that data remains in the list. Each subsequent call from your loop is seeing whatever previous calls put in it.
A simple solution to this as your code is written would be to simply add a second version that clears the list:
private List<DataEntity> beginRecursivellyParse(DataEntity entity,
JSONObject object) throws JSONException {
categories.clear();
return recursivellyParse(entity, object);
}
Then call that from your loop.
I have a json file formatted like this (only the actual file has no whitespace):
{
"main": [
{
"sections": [
"sec1",
"sec2"
],
"title": "Section List 1"
},
{
"sections": [
"sec3",
"sec4",
"sec5"
],
"title": "Section List 2"
}
],
"sections": {
"sec1": {
"products": [
"prod1",
"prod2"
]
},
"sec2": {
"products": [
"prod3"
]
}
},
"products": {
"prod1": {
"url": "url1.gif",
"title": "Product 1"
},
"prod2": {
"url": "url2.gif",
"title": "Product 2"
},
"prod3": {
"url": "url3.gif",
"title": "Product 3"
}
}
}
When I attempt to send the data for that file into JSONObject, the JSONObject being loaded only contains the final object in the top list, in this case "products". Right now, my code to load the JSONObject is this:
JSONObject dlResult = new JSONObject(new Scanner(cnxn.getInputStream()).nextLine());
I've also tried storing the data in a String first and giving that to the JSONObject constructor, I've tried giving that String to a JSONTokener first, and giving that tokener to the JSONObject constructor. Both the String and the JSONTokener contain the entire file, but once it gets put into the JSONObject, it's always the same thing - "main" and "sections" get cut out, and only "products" remains.
Here's the rest of my relevant code:
public class MapsListFragment extends ListFragment
{
private static JSONObject mDlResult;
private ArrayAdapter<MapInfo> mMapListAdapter = null;
private class MapInfo
{
private String mText;
private String mURL;
MapInfo(String inText, String inURL)
{
mText = inText;
mURL = inURL;
}
public String URL()
{
return mURL;
}
#Override
public String toString()
{
return mText;
}
}
public class MapsListUpdater extends AsyncTask<String, String, JSONObject>
{
private static final String URL = "http://jsonURL/products.json";
private Date lastUpdate;
#Override
protected JSONObject doInBackground(String... inObjects)
{
Date ifModifiedSince = lastUpdate;
try
{
HttpURLConnection cnxn = (HttpURLConnection) new URL(URL).openConnection();
if (ifModifiedSince != null)
cnxn.setIfModifiedSince(ifModifiedSince.getTime());
cnxn.connect();
if (cnxn.getResponseCode() != HttpURLConnection.HTTP_NOT_MODIFIED)
{
mDlResult = new JSONObject(new Scanner(cnxn.getInputStream()).nextLine());
}
cnxn.disconnect();
}
catch (Exception e)
{
boolean check = true;
}
return mDlResult;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
try
{
// This is really ugly and brute-forcey, but it's the only way I could get JSONObjects populated with ALL the data!
/*String[] tryThis = mDlResult.split(",\"sections\":");
tryThis[0] += '}';
tryThis[1] = tryThis[1].substring(0, tryThis[1].indexOf("]}},\"products\":"));
tryThis[1] = "{\"sections\":" + tryThis[1] + "]}}}";*/
JSONObject mainObj = mDlResult.getJSONObject("main");//new JSONObject(mDlResult);
JSONArray mainArray = mainObj.getJSONArray("main");
Vector<String> titles = new Vector<String>();
mMapListAdapter.clear();
for (int i = 0; i < mainArray.length(); i++)
{
JSONObject object = mainArray.getJSONObject(i);
String title = object.getString("title");
if(!titles.contains(title))
{
titles.add(title);
mMapListAdapter.add(new MapInfo(object.getString("title"), null));
}
}
}
catch (Exception e)
{
boolean check = true;
}
}
}
}
I feel a little foolish now. As it turns out, the JSONObject was getting EXACTLY what I asked it for... only the objects within it were getting reordered, so I couldn't see the first 2 objects in my debugger!
Try reading it into a JSONArray and let me know how you get on:
JSONArray dlResult = new JSONArray(cnxn.getInputStream());