如何使用GSON获取解析的数据

时间:2016-06-20 10:57:09

标签: java android arrays json gson

所以我跟着这个tutorial并且它有这个方法。

new AsyncTask<Void,Void,Void>(){

        @Override
        protected Void doInBackground(Void... voids) {

            Reader reader=API.getData("http://beta.json-generator.com/api/json/get/DiIRBM4");

            Type listType = new TypeToken<ArrayList<DoctorBean>>(){}.getType();
            beanPostArrayList = new GsonBuilder().create().fromJson(reader, listType);
            postList=new StringBuffer();
            for(DoctorBean post: beanPostArrayList){
                postList.append("\n heroName: "+post.getHeroName()+"\n realName: "+post.getRealName()+"\n\n");
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Log.d("JSON Result ", postList.toString());
        }
    }.execute();

日志结果仅显示这些值。

JSON结果:

  

heroName:null realName:null

     

heroName:null realName:null

     

heroName:null realName:null

这是我的JSON数据

[
{
    "heroName": "Dr. Strange",
    "realName": "Stephen Strange"
},
{
    "heroName": "Spider-Man",
    "realName": "Peter Paker"
},
{
    "heroName": "Captain America",
    "realName": "Stever Rogers"
}
]

这是我的数据模型

import com.google.gson.annotations.SerializedName;
public class DoctorBean {

    @SerializedName("heroName")
    private String heroName;

    @SerializedName("realName")
    private String realName;

    public DoctorBean(String heroName, String realName) {
        this.heroName = heroName;
        this.realName = realName;
    }

    public String getHeroName() {
        return heroName;
    }

    public void setHeroName(String heroName) {
        this.heroName = heroName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }
}

这是我的 API类

public class API {
    private static Reader reader=null;
    public static Reader getData(String SERVER_URL) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(SERVER_URL);
            HttpResponse response = httpClient.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                reader = new InputStreamReader(content);
            } else {
//              Log.e("error:", "Server responded with status code: "+ statusLine.getStatusCode());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reader;
    }
}

我注意到日志结果显示了3行,所以我认为它能够正确获取数组的长度。但至于数据,都是空的。

2 个答案:

答案 0 :(得分:0)

试试这个。 从响应中创建一个数组:

DoctorBean[] doctorBeanArray = new Gson().fromJson(response, DoctorBean[].class); // Where response is your string response

然后创建一个ArrayList:

ArrayList<DoctorBean> doctorBeanList = new ArrayList<DoctorBean>(Arrays.asList(doctorBeanArray));

答案 1 :(得分:0)

根据您提供的tutorial,来自this的链接响应如下:

    [
   {
      "date":"11/8/2014",
      "auther":"nirav kalola",
      "description":"json object parsing using gson library is easy",
      "post_name":"json object parsing"
   },
   {
      "date":"12/8/2014",
      "auther":"nirav kalola",
      "description":"json array parsing using gson library",
      "post_name":"json array parsing"
   },
   {
      "date":"17/8/2014",
      "auther":"nirav kalola",
      "description":"store json file in assets folder and get data when required",
      "post_name":"json parsing from assets folder"
   }
]

所以你需要在 GSONBuilder 下面尝试POJO类。将您的名字替换为 BeanPost

 import com.google.gson.annotations.SerializedName;
public class BeanPost {


@SerializedName("post_name")
private String post_name;
@SerializedName("auther")
private String auther;
@SerializedName("date")
private String date;
@SerializedName("description")
private String description;

public BeanPost(String post_name, String auther, String date, String description) {
    this.post_name = post_name;
    this.auther = auther;
    this.date = date;
    this.description = description;
}

public String getPost_name() {
    return post_name;
}
public void setPost_name(String post_name) {
    this.post_name = post_name;
}
public String getAuther() {
    return auther;
}
public void setAuther(String auther) {
    this.auther = auther;
}
public String getDate() {
    return date;
}
public void setDate(String date) {
    this.date = date;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
}

尝试按照上面的pojo类arraylist创建 beanPostArrayList 。并尝试使用您的代码并从中获取相应的字段。

我希望它会帮助你。