I'm creating Database from JSON. I get this error when I run app:
Problem parsing the news JSON results
org.json.JSONException: Value Trump of type java.lang.String cannot be converted to JSONObject
Here is code:
private static List<News> extractFeatureFromJson(String newsJSON) {
if (TextUtils.isEmpty( newsJSON )) {
return null;
}
List<News> newsall = new ArrayList<>();
try {
JSONObject data = new JSONObject(newsJSON);
JSONArray results = data.getJSONArray("articles");
for (int i = 0; i < results.length(); i++) {
JSONObject obj = results.getJSONObject(i);
String webTitle = obj.getString("title");
String webUrl = obj.getString("url");
String webImage = obj.getString( "urlToImage" );
List<NewsForDB> newsForDB = new ArrayList<>( );
Gson gson = new Gson();
NewsForDB webTitleForDB=gson.fromJson( extractFeatureFromJson( webTitle ).toString(), NewsForDB.class );
newsForDB.add(webTitleForDB);
NewsForDB urlForDB=gson.fromJson( extractFeatureFromJson( webUrl ).toString(), NewsForDB.class );
newsForDB.add(urlForDB);
NewsForDB webImageForDB=gson.fromJson( extractFeatureFromJson( webImage ).toString(), NewsForDB.class );
newsForDB.add( webImageForDB );
News news = new News(webTitle, webUrl, webImage);
newsall.add(news);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
return newsall;
}
When there are no this lines of code
List<NewsForDB> newsForDB = new ArrayList<>( );
Gson gson = new Gson();
NewsForDB webTitleForDB=gson.fromJson( extractFeatureFromJson( webTitle ).toString(), NewsForDB.class );
newsForDB.add(webTitleForDB);
NewsForDB urlForDB=gson.fromJson( extractFeatureFromJson( webUrl ).toString(), NewsForDB.class );
newsForDB.add(urlForDB);
NewsForDB webImageForDB=gson.fromJson( extractFeatureFromJson( webImage ).toString(), NewsForDB.class );
newsForDB.add( webImageForDB );
Everything works great, but I'm trying to prepare code to use ActiveAndroid ORM.
Any suggestions?
Thanks!
UPDATE:
I am following first answer from here.
News:
public class News {
private String mWebTitle;
private String mUrl;
private String mImage;
public News(String webTitle, String webUrl, String webImage) {
mWebTitle = webTitle;
mUrl = webUrl;
mImage = webImage;
}
public String getWebTitle() {
return mWebTitle;
}
public String getUrl() {
return mUrl;
}
public String getWebImage() {return mImage;}
}
And here is part of code from QueryUtils, which is before that posted in first question
public static List<News> fetchNewsData(String requestUrl) {
URL url = createUrl( requestUrl );
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest( url );
} catch (IOException e) {
Log.e( LOG_TAG, "Problem making the HTTP request.", e );
}
List<News> news = extractFeatureFromJson( jsonResponse );
return news;
}
And here is NewsForDB.java
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
#Table(name = "NewsDB")
public class NewsForDB extends Model {
#Column(name = "title", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
public String title;
#Column(name = "url")
public String url;
#Column(name = "urlToImage")
public String urlToImage;
public NewsForDB(){
super();
}
public NewsForDB(String title, String url, String urlToImage){
super();
this.title = title;
this.url = url;
this.urlToImage = urlToImage;
}
}
Thank You!
you can edit code just like this !
private static List<News> extractFeatureFromJson(String newsJSON) {
if (TextUtils.isEmpty( newsJSON )) {
return null;
}
List<News> newsall = new ArrayList<>();
try {
JSONObject data = new JSONObject(newsJSON);
JSONArray results = data.getJSONArray("articles");
for (int i = 0; i < results.length(); i++) {
Gson gson = new Gson();
JSONObject obj = results.getJSONObject(i);
News news = gson.fromJson(obj.toString() , News.class);
newsall.add(news);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
return newsall;
}
I think problem occurs when you make recursive in function extractFeatureFromJson when you call extractFeatureFromJson( webTitle ), and so on.
Maybe you should share your class News, NewsForDB, testcases which make exception, and can you tell me the purpose you create an object newsForDB without usage?
Related
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()
how to deserialize below string in android. I have tried below
String json= ls.get(j).getCwc();
Example example = new Gson().fromJson(json,Example.class);
Json
[{
"company":"gjjzh",
"AvgSal":"hjsj"
},
{
"company":"hjd",
"AvgSal":"hjd"
},
{
"company":"hm",
"AvgSal":"lk"
},
{
"company":"er",
"AvgSal":"io"
},
{
"company":"uo",
"AvgSal":"tr"
}]
String json= ls.get(j).getCwc();
Type type = new TypeToken<List<Example>>(){}.getType();
List<Example> example = new Gson().fromJson(json,type);
where Example is
public class Example {
#SerializedName("company")
#Expose
private String company;
#SerializedName("AvgSal")
#Expose
private String avgSal;
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getAvgSal() {
return avgSal;
}
public void setAvgSal(String avgSal) {
this.avgSal = avgSal;
}
}
You'll need to create a model class for the object.
Example.java
public class Example{
String company = "";
String AvgSal = "";
}
and then you need to write code as below to convert JSONArray string into List<Model>.
String json= ls.get(j).getCwc();
Type modelListType = new TypeToken<ArrayList<Example>>(){}.getType();
ArrayList<Example> modelList = new Gson().fromJson(json, modelListType);
This will convert JSONArray into ArrayList.
String url = Config.DATA_URL+TempItem.toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
This is the constructor where I parse in my response.
I am a total beginner in android studio and I have no idea how to solve this error. I have read other forums which I tried implementing to no avail. My JSON result is
"result":[
{
"BusinessName":"KachangPuteh",
"AmountTotal":"100",
"RequiredTotal":"200",
"MaxTotal":"500"
}
]
}
private void showJSON(String response){
String name="";
String AmountTotal="";
String RequiredTotal = "";
String MaxTotal = "";
try {
JSONObject jsonObject = new JSONObject(response);
String results= jsonObject.getString(Config.JSON_ARRAY);
JSONArray result = new JSONArray(results);
JSONObject stallsData = result.getJSONObject(0);
name = stallsData.getString(Config.KEY_NAME);
AmountTotal = stallsData.getString(Config.KEY_AmountTotal);
MaxTotal = stallsData.getString(Config.KEY_MT);
RequiredTotal = stallsData.getString(Config.KEY_RT);
} catch (JSONException e) {
e.printStackTrace();
Log.e("error ",e.getMessage());
}
Stall.setText("Name:\t"+name+"\nAmountTotal:\t" +AmountTotal+ "\nMaxTotal:\t"+ MaxTotal);
}
This is to change my JSONObject to JSONArray.
Edit:
This is my php file
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('conn.php');
$sql = "SELECT * FROM business WHERE BusinessID='".$id."'";
$r = mysqli_query($conn,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"BusinessName"=>$res["BusinessName"],
"AmountTotal"=>$res["AmountTotal"],
"RequiredTotal"=>$res["RequiredTotal"],
"MaxTotal"=>$res["MaxTotal"]
)
$str = json_encode(array("result"=>$result)); $str=str_replace('','',$str); $str=str_replace('','',$str); echo $srt;
echo json_encode(array("result"=>$result));
);
mysqli_close($conn);
}
this is my config file.
public class Config {
public static final String DATA_URL = "http://192.168.1.2/retrieveone.php?id=";
public static final String KEY_NAME = "BusinessName";
public static final String KEY_AmountTotal = "AmountTotal";
public static final String KEY_RT = "RequiredTotal";
public static final String KEY_MT = "MaxTotal";
public static final String JSON_ARRAY = "result";
}
You are parsing data wrongly. Try below code -
JSONArray result = jsonObject.getJSONArray("result");
JSONObject stallsData = result.getJSONObject(0);
Here i am doing some changes in your code .
{"result":[
{
"BusinessName":"KachangPuteh",
"AmountTotal":"100",
"RequiredTotal":"200",
"MaxTotal":"500"
} ] }
this will be your actual response.
now i am going to parse it.
` private void showJSON(String response){
String name="";
String AmountTotal="";
String RequiredTotal = "";
String MaxTotal = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result"); // this line is new
for(int i=0;i<result.length;i++){
JSONObject stallsData = result.getJSONObject(i);
name = stallsData.getString(Config.KEY_NAME);
AmountTotal = stallsData.getString(Config.KEY_AmountTotal);
MaxTotal = stallsData.getString(Config.KEY_MT);
RequiredTotal = stallsData.getString(Config.KEY_RT);
} catch (JSONException e) {
e.printStackTrace();
Log.e("error ",e.getMessage());
}
}Stall.setText("Name:\t"+name+"\nAmountTotal:\t" +AmountTotal+ "\nMaxTotal:\t"+ MaxTotal);
}
you can write
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("result");
pDialog.dismiss();
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String BusinessName= jo.getString("BusinessName");
String AmountTotal= jo.getString("AmountTotal");
String RequiredTotal= jo.getString("RequiredTotal");
String MaxTotal= jo.getString("MaxTotal");
}
} catch (JSONException e) {
e.printStackTrace();
}
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 :)
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 )