【问题标题】:How to parse json object in Android?如何在 Android 中解析 json 对象?
【发布时间】:2016-08-03 08:52:11
【问题描述】:

我正在尝试解析 Json 对象;

{
   "results":[
      {
         "face":{
            "id":361122.0,
            "photo_hash":"0a2aaff34fd576fc1caf711d88cbfd53",
            "x1":699,
            "x2":1020,
            "y1":271,
            "photo":" ",
            "thumbnail":" ",
            "meta":"",
            "timestamp":"2016-07-28T08:50:43.710183",
            "y2":592
         },
         "confidence":0.93187
      },
      {
         "face":{
            "id":361260.0,
            "photo_hash":"767bf4df0c8a04361aaf5e6b74eb4d8c",
            "x1":-25,
            "x2":147,
            "y1":10,
            "photo":" ",
            "thumbnail":" ",
            "meta":"",
            "timestamp":"2016-07-28T15:13:09.086390",
            "y2":165
         },
         "confidence":0.926754
      }
   ]
}

我正在使用这样的代码来解析 confidencethumbnail

resultParams[i].confidence = jsonObject.getJSONArray("results").getJSONObject(i).getString("confidence");

resultParams[i].thumbnail = jsonObject.getJSONArray("results").getJSONObject(i).getJSONObject("face").getString("thumbnail");

但是它给出了异常"java.lang.NullPointerException: Attempt to write to field on a null object reference"

你能帮我如何成功解析它吗?

【问题讨论】:

  • 请发布您的代码 :)
  • @HuyN 我已经发布了!请看问题
  • 你检查resultParams[i]不为空吗?
  • 没错,因为它指出Attempt to write to field 未读,所以= 的左侧是问题
  • 更多代码请,这两行不能帮助我们找出问题。

标签: java android json parsing


【解决方案1】:

给出答案:

"java.lang.NullPointerException: 尝试写入字段 在空对象引用上"

表示您的左侧是问题所在。 resultParams[i] 很可能为空。

【讨论】:

    【解决方案2】:

    如果你知道你会收到什么样的 json 对象(或者你有一个 API),你可以通过例如 Jackson 库来制作这个类的对象。然后通过 getter 访问“face”对象。

    yourObject.getResults().get(i).getFace().getThumbnail();
    

    【讨论】:

      【解决方案3】:

      首先根据您创建模型对象的 JSON 响应。 您可以利用 GS​​ON 将整个内容转换为对象。 这也可以使用其他库来实现。

      这里是您的 JSON 的模型对象

      import java.util.Date;
      import java.util.List;
      class Result {
          private List<PersonDetails> results;
          // generate setter and getter
      }
      class PersonDetails
      {
          private ImageDetail face;
          private Float confidence;
          // generate setter and getter
      }
      
      class ImageDetail
      {
          private Long id;
          private String photo_hash;
          private Integer x1,x2,y1,y2;
          private String thumbnail;
          private String meta;
          private String photo;
          private Date timestamp;
          // generate setter and getter
      }
      

      现在使用 GSON 转换您的 JSON。

      public class JsonTransaformer1 {
      
      @SuppressWarnings("unchecked")
      public static void main(String[] args) {
          String text = "Place your JSON Response as input that you posted";
          Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonUTCdateAdapter()).create();
          Result obj = gson.fromJson(text, Result.class);
          System.out.println(obj.getResults().size());
          System.out.println(obj.getResults().get(0).getFace().getId());
          System.out.println(obj.getResults().get(0).getConfidence());
      }
      

      }

      由于您的 JSON 响应中存在的日期格式不同,我们需要注册适配器来解析日期。 查看此链接进行解析

      Java Date to UTC using gson

      class GsonUTCdateAdapter implements JsonSerializer<Date>,JsonDeserializer<Date> {
      
      private final DateFormat dateFormat;
      
      public GsonUTCdateAdapter() {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);      //This is the format I need
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));                               //This is the key line which converts the date to UTC which cannot be accessed with the default serializer
      }
      
      @Override public synchronized JsonElement serialize(Date date,Type type,JsonSerializationContext jsonSerializationContext) {
          return new JsonPrimitive(dateFormat.format(date));
      }
      
      @Override public synchronized Date deserialize(JsonElement jsonElement,Type type,JsonDeserializationContext jsonDeserializationContext) {
        try {
          return dateFormat.parse(jsonElement.getAsString());
        } catch (ParseException e) {
          throw new JsonParseException(e);
        }
      }
      }
      

      现在运行主程序,您将获得 JSON 的对象表示。

      【讨论】:

        猜你喜欢
        • 2011-07-30
        • 2015-11-26
        • 1970-01-01
        • 2016-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        相关资源
        最近更新 更多