有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解析json到安卓中活动中的对象

我有一个返回JSON的php脚本,如下所示:

[{"title":"Clothes are selling well","location":"Los Angeles","imageUrl":"xxx","pubDate":"2014-07-26 13:58:08","id":"1"},{"title":"Polo  this summer","location":"UAE","imageUrl":"YYY","pubDate":"2014-07-26 18:05:26","id":"2"},{"title":"Samsung: New tablets","location":"Kuwait","imageUrl":"IIIIII","pubDate":"2014-07-26 18:05:26","id":"3"}]

我需要在我的活动类中解析这个json。有什么建议吗?我将创建具有以下属性的对象:

  1. 头衔
  2. 位置
  3. 图像URL
  4. 出版日期

提前谢谢


共 (3) 个答案

  1. # 1 楼答案

    根据这些属性创建类。 下载谷歌的Gson 类示例名称:Objects 例如:

    String json = "....";
    Gson gson = new Gson();
    Objects obj = (Objects) gson.fromJson(json,Objects.class);
    

    希望能有帮助

  2. # 2 楼答案

    在Android中解析JSON非常容易。这就是如何解析当前的JSON-

       //Assuming json holds your JSON as String
       try {
            //Create a JSON array 
            JSONArray jsonArray = new JSONArray(json);
    
            //Iterate through all the JSON objects
            for(int i=0;i<jsonArray.length();i++){
    
                //Get ith object
                JSONObject item = jsonArray.getJSONObject(i);
    
                //Get required data from the object
                String title = (String) item.get("title");
                String location = (String) item.get("location");
                String imageUrl = (String) item.get("imageUrl");
                String pubDate = (String) item.get("pubDate");
    
                //You can now do anything with the data.
                Log.i("TITLE", title);
                Log.i("LOC", location);
                Log.i("IMG_URL", imageUrl);
                Log.i("P_DATE", pubDate);                           
    
            }                       
    
        } catch (JSONException e) {
            Log.i("EXP", "Ooi..! There's an exception.");
            e.printStackTrace();
        }
    

    如果您是解析JSON的新手,有很多简单的教程,比如-

  3. # 3 楼答案

    Jackson library帮助您自动将数据绑定到JSON或从JSON绑定数据

    public class Object {
      @JsonProperty
      private  String title;
      @JsonProperty
      private String location;
      @JsonProperty
      private String url;
    
      @JsonPropery
      private String pubDate;
      @JsonProperty
      private int id;
    
      //Add set and get method.
    }
    

    为了解析字符串,需要使用ObjectMapper对象

    ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
    Object obj = mapper.readValue(/*your string*/, Object.class);
    

    否则,您可以使用Android JSONTokener轻松地手动完成