How to convert Json array to List<string>? - android

Here's the JSON I'm parsing.
<item>{\"name\":{\"mainName\":\"Ham and cheese
sandwich\",\"alsoKnownAs\":[]},\"placeOfOrigin\":\"\",\"description\":\"A ham and cheese
sandwich is a common type of sandwich. It is made by putting cheese and sliced ham
between two slices of bread. The bread is sometimes buttered and/or toasted. Vegetables
like lettuce, tomato, onion or pickle slices can also be included. Various kinds of
mustard and mayonnaise are also
common.\",\"image\":\"https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/Grilled_ham_and_cheese_014.JPG/800px-Grilled_ham_and_cheese_014.JPG\",\
"ingredients\":[\"Sliced
bread\",\"Cheese\",\"Ham\"]}
alsoKnownAs and ingredients arrays don't have keys. I need to convert them to lists and add them to the Sandwich object. Currently, it doesn't work. I thought the code inside the for loop would be enough. Can someone please take a look? Thank you in advance.
I based my code on the answers in this thread: Converting JSONarray to ArrayList
Also, one of the posters in the above thread suggested using a helper method from this link(line 45).
https://gist.github.com/codebutler/2339666
My code:
public static Sandwich parseSandwichJson(String json) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(json)) {
return null;
}
Sandwich sandwiches = null;
try {
// Create a JSONObject from the JSON file
JSONObject jsonObject = new JSONObject(json);
//fetch JSONObject named name
JSONObject objectName = jsonObject.getJSONObject("name");
// Extract the value for the key called "main_name"
String mainName = "";
if (objectName.has("mainName")) {
mainName = objectName.optString(KEY_MAIN_NAME);
}
JSONArray alsoKnownAsArray = objectName.optJSONArray(KEY_ALSO_KNOWN_AS);
List<String> alsoKnownData = new ArrayList();
for (int i = 0; i < alsoKnownAsArray.length(); i++) {
alsoKnownData.add(alsoKnownAsArray.getString(i));
}
String placeOfOrigin = "";
if (objectName.has("placeOfOrigin")) {
placeOfOrigin = objectName.optString(KEY_PLACE_OF_ORIGIN);
}
String description = "";
if (objectName.has("description")) {
description = objectName.optString(KEY_DESCRIPTION);
}
String image = "";
if (objectName.has("image")) {
image = objectName.optString(KEY_IMAGE);
}
JSONArray ingredientsArray = objectName.optJSONArray(KEY_INGREDIENTS);
List<String> ingredientsData = new ArrayList<String>();
if (ingredientsArray != null) {
for (int i = 0; i < ingredientsArray.length(); i++) {
ingredientsData.add(ingredientsArray.getString(i));
}
}
Sandwich sandwich = new Sandwich(mainName, alsoKnownAsArray, placeOfOrigin, description, image, ingredientsArray);
sandwiches.add(sandwich);
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing sandwich JSON results", e);
}
// Return the list of sandwiches
return sandwiches;
}

You can parse the JSON this way:
public class JsonUtils {
public static Sandwich parseSandwichJson(String json) {
try {
JSONObject mainJsonObject = new JSONObject(json);
JSONObject name = mainJsonObject.getJSONObject("name");
String mainName = name.getString("mainName");
JSONArray alsoKnownAsArray = name.getJSONArray("alsoKnownAs");
List<String> alsoKnownAs = new ArrayList<>(alsoKnownAsArray.length());
for ( int i = 0; i < alsoKnownAsArray.length(); i++ ) {
alsoKnownAs.add(alsoKnownAsArray.getString(i));
Log.i("alsoKnownAs", "I am here" + alsoKnownAs);
}
String placeOfOrigin = mainJsonObject.optString("placeOfOrigin");
String description = mainJsonObject.getString("description");
String image = mainJsonObject.getString("image");
JSONArray ingredientsArray = mainJsonObject.getJSONArray("ingredients");
List<String> ingredients = new ArrayList<>(ingredientsArray.length());
for ( int i = 0; i < ingredientsArray.length(); i++ ) {
Log.i("ingredients", "These are the ingredients" + ingredients);
ingredients.add(ingredientsArray.getString(i));
}
return new Sandwich(mainName, alsoKnownAs, placeOfOrigin, description, image, ingredients);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

Use Gson for parsing (https://github.com/google/gson)
Add this 2 class for data handle
public class CustomData
{
private List<String> ingredients;
private String placeOfOrigin;
private String description;
private Name name;
private String image;
public List<String> getIngredients ()
{
return ingredients;
}
public void setIngredients (List<String> ingredients)
{
this.ingredients = ingredients;
}
public String getPlaceOfOrigin ()
{
return placeOfOrigin;
}
public void setPlaceOfOrigin (String placeOfOrigin)
{
this.placeOfOrigin = placeOfOrigin;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public Name getName ()
{
return name;
}
public void setName (Name name)
{
this.name = name;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
}
Class Name:
public class Name
{
private String[] alsoKnownAs;
private String mainName;
public String[] getAlsoKnownAs ()
{
return alsoKnownAs;
}
public void setAlsoKnownAs (String[] alsoKnownAs)
{
this.alsoKnownAs = alsoKnownAs;
}
public String getMainName ()
{
return mainName;
}
public void setMainName (String mainName)
{
this.mainName = mainName;
}
}
Function to parse JSON to Object
public CustomData parseJsonToData(String jsonString) {
CustomData data = new Gson().fromJson(jsonString, CustomData.class);
return data;
}
So you can get List by
CustomData data = parseJsonToData(jsonString)
List<String> ingredients = data.getIngredients()

Related

JSON parsing for an array with two arraylists inside [duplicate]

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()

How do I convert an object that contains and arraylist of other objects into JSON for sending to an API - Android

Imagine I have an object - ChildObject. ChildObject has 3 properties. Id, Name, Age.
I also have another object - ParentObject. ParentObject also has 3 properties. Id, Date but the 3rd is ArrayList of ChildObjects Family.
How would I go about converting this into a JSONObject to be able to send it over to a RESTfull WebAPI service.
So far I have failed to find anything that works, and I'm struggling to wrap my head around the problem.
To make it more of a challenge I cant use 3rd party extentions (eg gson etc).
Thanks in advance for your help.
Adding Objects to see if they make it any clearer
ParentObject
public class JobMovementRequestDto {
public String Id_Employee;
public String ActionDate;
public String Id_Terminal;
public String Id_Device;
public ArrayList<JobActivityRequestDto> FromJobs;
public ArrayList<JobActivityRequestDto> ToJobs;
public JobMovementRequestDto(){
}
public JobMovementRequestDto(String idEmployee, String activityDate, String idTerminal, String idDevice, ArrayList<JobActivityRequestDto> fromItems, ArrayList<JobActivityRequestDto> toItems){
this.Id_Employee = idEmployee;
this.ActionDate = activityDate;
this.Id_Terminal = idTerminal;
this.Id_Device = idDevice;
this.FromJobs = fromItems;
this.ToJobs = toItems;
}
public String getIdEmployee() {return this.Id_Employee;}
public String getActivityDate() {return this.ActionDate;}
public String getIdTerminal() {return this.Id_Terminal;}
public String getIdDevice() {return this.Id_Device;}
public ArrayList<JobActivityRequestDto> getFromList() {return this.FromJobs;}
public ArrayList<JobActivityRequestDto> getToLIst() { return this.ToJobs;}
ChildObject
public class JobActivityRequestDto {
public String Id_Job;
public String Id_Batch;
public String Id_ActivityType;
public JobActivityRequestDto()
{
}
public JobActivityRequestDto(String idJob, String idBatch, String idActivityType)
{
this.Id_Job = idJob;
this.Id_Batch = idBatch;
this.Id_ActivityType = idActivityType;
}
public String getIdJob() { return this.Id_Job;}
public String getIdBatch() {return this.Id_Batch;}
public String getIdActivityType() {return this.Id_ActivityType;}
}
Here is your complete solution, Please check.
public void makeJsonObject()
{
try
{
JSONObject parentJsonObject = new JSONObject();
parentJsonObject.put("Id", parentObject.getId());
parentJsonObject.put("Id", parentObject.getDate());
JSONArray childListArr = new JSONArray();
for (int i = 0; i < parentObject.ChildObjectsList().size(); i++)
{
ChildObject childObject = parentObject.ChildObjectsList().get(i);
JSONObject childJsonObject = new JSONObject();
childJsonObject.put("id", childObject.getId());
childJsonObject.put("Name", childObject.getName());
childJsonObject.put("Age", childObject.getAge());
childListArr.put(childJsonObject);
}
parentJsonObject.put("childList", childListArr);
Log.e(TAG, "parentJsonObject=="+parentJsonObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
JSONObject fromObject, toObject, parentObject;
JSONArray fromArray, toArray;
JobMovementRequestDto JMRD = new JobMovementRequestDto();
try {
parentObject = new JSONObject();
parentObject.put("Id_Employee", JMRD.getIdEmployee());
parentObject.put("ActionDate", JMRD.getActivityDate());
parentObject.put("Id_Terminal", JMRD.getIdTerminal());
parentObject.put("Id_Device", JMRD.getIdDevice());
fromArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getFromList()){
//Loop your multiple childObjects and add it childArray
fromObject = new JSONObject();
fromObject.put("Id_Job",JARD.getIdJob());
fromObject.put("Id_Batch",JARD.getIdBatch());
fromObject.put("Id_ActivityType",JARD.getIdActivityType());
fromArray.put(fromObject);
}
toArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getToLIst()){
//Loop your multiple childObjects and add it childArray
toObject = new JSONObject();
toObject.put("Id_Job",JARD.getIdJob());
toObject.put("Id_Batch",JARD.getIdBatch());
toObject.put("Id_ActivityType",JARD.getIdActivityType());
toArray.put(toObject);
}
//Finally, Add childArray to ParentObject.
parentObject.put("fromObjects",fromArray);
parentObject.put("toObjects",toArray);
} catch (JSONException e) {
e.printStackTrace();
}
Create a JSON like this and You Can Send This to Your Server. I Hope This Is What You Want Right?

how to get json values in an array

I am completely don't know Json. Now i am working in Android project. I know how to use Array. I have Json file inside of my Asset folder in my Android Project.
and i have to fetch only standard value from json data and store it in an empty array. my json data is,
[
{
"name":"aaa",
"surname":"bbb",
"age":"18",
"div":"A",
"standard":"7"
},
{
"name":"ccc",
"surname":"ddd",
"age":"17",
"div":"B",
"standard":"7"
},
{
"name":"eee",
"surname":"fff",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"ggg",
"surname":"hhh",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"sss",
"surname":"ddd",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"www",
"surname":"ggg",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"ggg",
"surname":"ccc",
"age":"18",
"div":"B",
"standard":"6"
}
]
i am not able to get the way through which i can do this. because i have to check each standard in json data and add it to the array created for storing standard valuee so that i can compare that standard values with each satndard values if its already present in array the it can check the next index in josn data and accordingly unique values can get stored on may array.
i dont know to achieve this as i am new to android as well as for json.
Use gson for easy parsing of json
TypeToken> token = new TypeToken>() {};
List animals = gson.fromJson(data, token.getType());
you can use http://www.jsonschema2pojo.org/ to create user class
public class User {
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("age")
#Expose
private String age;
#SerializedName("div")
#Expose
private String div;
#SerializedName("standard")
#Expose
private String standard;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getDiv() {
return div;
}
public void setDiv(String div) {
this.div = div;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
}
You can do this way:
//Global Declared
ArrayList<String> allStanderds = new ArrayList<>();
allStanderds.clear();
try{
JSONArray araay = new JSONArray(Your_Json_Array_String);
for (int i = 0; i <array.length() ; i++) {
JSONObject jsonObject = new array.getJSONObject(i);
String standard = jsonObject.getString("standard");
if(!allStanderds.contains(standard)){
allStanderds.add(standard);
}
}
}catch (Exception e) {
e.printStackTrace();
}
// use allStanderds ArrayList for SetAdapter for Spinner.
Happy Coding > :)
Use GSON for parsing JSON array.GSON will provide very helpful API
See my previously asked question on SO related to JSON parsing. You will get rough idea
How to parse nested array through GSON
installl GsonFormat plugin in android studio
use your json string to generate an user entity(example:UserEntity.class)
now,you can use UserEntity user=new Gson().fromJson(yourString,UserEntity.class);
now,your json string is storaged in Object user now;
Please try to use this one
try{
String assestValue = getStringFromAssets();
JSONArray arr = new JSONArray(assestValue);
int count = arr.length();
for (int i=0; i < count; i++){
JSONObject obj = arr.getJSONObject(i);
String name = obj.getString("name");
String surname = obj.getString("surname");
String age = obj.getString("age");
String div = obj.getString("div");
String standard = obj.getString("standard");
}
}catch (JSONException e){
e.printStackTrace();
}
public String getStringFromAssets(){
String str = "";
try {
StringBuilder buf = new StringBuilder();
InputStream json = getAssets().open("contents.json");//put your json name
BufferedReader in =
new BufferedReader(new InputStreamReader(json, "UTF-8"));
while ((str = in.readLine()) != null) {
buf.append(str);
}
in.close();
return str;
}catch (Exception e){
e.printStackTrace();
}
return str;
}
Enjoy programming :)

Using the MyWeather2 web service in android

I am new to android , and I need an example to use / consume the following Web service in an application developed on android studio :
http://www.myweather2.com/developer/weather.ashx?uac=ENHRNh-psb&uref=53694bca-82a0-4de3-8a9b-70e4fe0b3e94
I would be very useful to be very specific.
Use JSON API instead of XML, that will make your task easier.
public class QueryBuilder {
//This is your unique key as I can see in the URL
private static final String KEY = "ENHRNh-psb";
// Take output as JSON instead of XML
private static final String OUTPUT = "json";
private static final String BASE_URL = "http://www.myweather2.com/developer/weather.ashx?";
private String query;
public QueryBuilder() {
//build the base query with key and output
this.query = BASE_URL + "uac=" + KEY + "&output=" + OUTPUT;
}
//Example of methods which you can add according to your requirement
public QueryBuilder setLocalityFilter(String locality) {
this.query = this.query + "&filters={\"locality\":{\"$eq\":\"" + locality + "\"}}";
return this;
}
public String build() {
return this.query;
}
}
Example of JSON parser class
public class JsonParser {
public static ArrayList<Restaurant> parseHTTPResponse(String responseString) {
ArrayList<Restaurant> restaurantArrayList= new ArrayList<>();
try {
JSONObject baseObject = new JSONObject(responseString);
JSONObject responseObject = baseObject.getJSONObject("response");
JSONArray restaurantArray = responseObject.getJSONArray("data");
for (int i =0; i<restaurantArray.length();i++) {
Restaurant restaurant = new Restaurant();
JSONObject restaurantObject = restaurantArray.getJSONObject(i);
restaurant.setName(restaurantObject.getString("name"));
restaurant.setAddress(restaurantObject.getString("address"));
restaurant.setRating(restaurantObject.getDouble("rating"));
// Check if the restaurant has its cuisine listed, if yes add it to type
if(restaurantObject.has("cuisine")) {
JSONArray cuisineArray = restaurantObject.getJSONArray("cuisine");
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < cuisineArray.length(); j++) {
String cuisine = cuisineArray.getString(j);
stringBuilder.append(cuisine);
stringBuilder.append(" ,");
}
restaurant.setType(stringBuilder.toString());
}
restaurantArrayList.add(restaurant);
}
}
catch (JSONException ex) {
ex.printStackTrace();
}
return restaurantArrayList;
}
}
Build the query like this
String httpQuery = new QueryBuilder().setLocalityFilter(query).build();
try {
HttpRequest request = HttpRequest.get(httpQuery);
if (request.ok()) {
String response = request.body();
restaurantArrayList = JsonParser.parseHTTPResponse(response);
}
return restaurantArrayList;
} catch (HttpRequest.HttpRequestException exception) {
return null;
}

When added JSONObject method, Limited Json in Android

I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts.
But i have strange problem! when added this line in my codes, json and RecyclerView has limited and show 5 post instance of 10 posts!
code :
JSONObject imagesPair=images.getJSONObject("martial-frontpage-blog");
when added this line limited for 5 post, when delete this line it's ok and show 10 posts!
Json Link: Json link
AsyncTask codes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
JSONObject images=postObject.getJSONObject("thumbnail_images");
JSONObject imagesPair=images.getJSONObject("martial-frontpage-blog");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString("thumbnail")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
How can i fix this problem and when added above code, show 10 posts and run success application ? Thanks
how to use Gson here
first, add in your build.gradle this
dependencies {
compile 'com.google.code.gson:gson:2.4'
//your all other dependencies
}
second, create class PostsResponse and write in it
package your.package.here;
import android.text.TextUtils;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class PostsResponse {
private static final String DEFAULT_IMAGE_URL = "put your default image url here";
public static class Post {
#SerializedName("id")
private int mId;
#SerializedName("title")
private String mTitle;
#SerializedName("content")
private String mContent;
#SerializedName("thumbnail")
private String mThumbnail;
#SerializedName("thumbnail_images")
private Images mImages;
public static class Images {
#SerializedName("martial-frontpage-blog")
private String mMartialFrontpageBlogUrl;
public String getMartialFrontpageBlogImage() {
return TextUtils.isEmpty(mMartialFrontpageBlogUrl) ?
DEFAULT_IMAGE_URL :
mMartialFrontpageBlogUrl;
}
}
public int getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public String getContent() {
return mContent;
}
public String getThumbnail() {
return mThumbnail;
}
public String getMartialFrontpageBlogImage() {
return mImages.getMartialFrontpageBlogImage();
}
}
#SerializedName("posts")
private ArrayList<Post> mPosts;
public ArrayList<Post> getPosts() {
return mPosts;
}
}
and change part of your MainDataInfo from
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
JSONObject images=postObject.getJSONObject("thumbnail_images");
JSONObject imagesPair=images.getJSONObject("martial-frontpage-blog");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString("thumbnail")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
to this new one
if (!TextUtils.isEmpty(ou_response)) {
try {
PostsResponse postsResponse = new Gson().fromJson(ou_response, PostsResponse.class);
infoModels = new ArrayList<>();
for (PostsResponse.Post post : postsResponse.getPosts()) {
infoModels.add(new MainDataModel(
post.getId(),
post.getTitle(),
post.getContent(),
post.getThumbnail())
);
//// TODO: 26.04.16 use post.getMartialFrontpageBlogImage()
//// as you want here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
don't forget to properly fill DEFAULT_IMAGE_URL and package
and see TODO section
feel free to add new fields to Post class and provide getters for them
THE END )
"post" with index 5 in your server response has no "martial-frontpage-blog" in "thumbnail_images", so your parsing cycle simply stops and drops exception.
to fix it - use optJSONObject();imagesPair = images.optJSONObject("..."); and check it for null
one else moment )
fix your cycle from for (int i = 0; i <= infoModels.size(); i++) {
to for (int i = 0; i < postsArray.length(); i++) {
in your current realization cycle stops work by exception )

Categories

Resources