【问题标题】:How do I get the parsed data using GSON如何使用 GSON 获取解析后的数据
【发布时间】:2016-06-20 10:57:09
【问题描述】:

所以我关注了这个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 行,所以我认为它能够正确获取数组的长度。但是数据方面,都是空的。

【问题讨论】:

  • 您正在尝试获取 json 数据的链接是为您的 json 提供不同的 json。所以你需要根据真实的 json 响应创建 POJO 类。

标签: java android arrays json gson


【解决方案1】:

根据您给定的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;
}
}

尝试创建 beanPostArrayList 如上 pojo 类数组列表。并尝试您的代码并从中获取适当的字段。

希望对你有所帮助。

【讨论】:

    【解决方案2】:

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

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

    然后创建一个 ArrayList :

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

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多