2016-08-03 113 views
0

我想解析Json對象;如何解析Android中的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"

能否請你幫我如何成功地解析呢?

+0

請發佈您的代碼:) – alway5dotcom

+0

@HuyN我已經發布!請參閱問題 – goGud

+2

您是否檢查過'resultParams [i]'不爲null? – Fildor

回答

2

爲了給這個答案:

「顯示java.lang.NullPointerException:嘗試寫上一個空對象引用現場

意味着你的左側是問題。 resultParams[i]最有可能爲空。

0

如果你知道你會收到什麼類型的json對象(或者你有一個API),你可以通過例如Jackson庫來創建這個類的對象。然後用getter訪問「face」對象。

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

首先基於JSON響應創建模型對象。 您可以利用GSON將整個內容轉換爲對象。 這也可以使用其他庫文件來實現。

所以這裏的模型對象爲您的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的對象表示。