简体   繁体   English

如何在Android中解析json对象?

[英]How to parse json object in Android?

I am trying to parse Json object which is; 我试图解析的是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
      }
   ]
}

And I am using such code for parsing confidence and thumbnail : 我正在使用这样的代码来解析confidencethumbnail

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

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

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

Could you please help me how to successfully parse it? 您能帮我成功解析吗?

To give this an answer: 给这个答案:

"java.lang.NullPointerException: Attempt to write to field on a null object reference " “ java.lang.NullPointerException:尝试在空对象引用上 写入字段

Means your left side is the problem. 意味着您的左侧是问题。 resultParams[i] is most probably null. resultParams[i]最有可能为null。

If you know what kind of json-object will you receive(or maybe you have an API), you can make an object of this class by for example Jackson library. 如果您知道将接收哪种json对象(或者可能有API),则可以通过例如Jackson库来制作此类的对象。 And then get access to "face" object with its getter. 然后使用其吸气剂访问“面部”对象。

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

Firstly based on the JSON response you create your model object. 首先,基于JSON响应,创建模型对象。 You can make use of GSON for converting the whole content into object. 您可以利用GSON将整个内容转换为对象。 This can be acheived using other libaries too. 也可以使用其他库来实现。

So here are the Model objects for your JSON 这是JSON的Model对象

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
}

Now use GSON to convert your JSON. 现在使用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());
}

} }

As the Date format that is present in your JSON response is different we need to register the Adapter to parse the date. 由于JSON响应中存在的日期格式不同,因此我们需要注册适配器以解析日期。 Look into this link for parsing 查看此链接进行解析

Java Date to UTC using gson 使用gson将Java Date转换为UTC

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);
  }
}
}

Now running the main you will get the Object representation of JSON. 现在运行main,您将获得JSON的Object表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM