我在Android应用程序上工作,我遇到了Json String的问题。我想访问" Naam"在" Docenten"在下面的Json中:
{
"Items":[
{
"Id":2157750,
"Links":[
{
"Rel":"Self",
"Href":"/api/personen/11824/afspraken/2157750"
},
{
"Rel":"Next",
"Href":"/api/personen/11824/afspraken/2157661"
}
],
"Start":"2015-11-16T07:30:00.0000000Z",
"Einde":"2015-11-16T08:20:00.0000000Z",
"LesuurVan":1,
"LesuurTotMet":1,
"DuurtHeleDag":false,
"Omschrijving":"du - rec - G3A",
"Lokatie":"103",
"Status":7,
"Type":13,
"WeergaveType":0,
"Inhoud":"<html><head></head><body style=\"font-family: 'Arial'; font-size: 12px\"><p style=\"margin: 0px 0px 10px\">lernen für Klassenarbeit,<br/>fertigmachen: 17.4</p></body></html>",
"InfoType":1,
"Aantekening":null,
"Afgerond":false,
"Vakken":[
{
"Id":3,
"Naam":"Duits"
}
],
"Docenten":[
{
"Id":706,
"Naam":"C. Reuten",
"Docentcode":"rec"
}
],
"Lokalen":[
{
"Naam":"103"
}
],
"Groepen":null,
"OpdrachtId":0,
"HeeftBijlagen":false,
"Bijlagen":null
},
...
这是我的代码,但它提供了NullPointer错误:
private void handlejson_agenda(String input){
if(input != null && input != "[]" && input != "") {
try {
JSONObject jsonRootObject = new JSONObject(input);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("Items");
//Iterate the jsonArray and print the info of JSONObjects
if(jsonArray == null){
//niks
} else {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("Omschrijving").toString();
String lesuurvan = jsonObject.optString("LesuurVan").toString();
String lesuurtot = jsonObject.optString("LesuurTotMet").toString();
String lokatie = jsonObject.optString("Lokatie").toString();
String status = jsonObject.optString("Status").toString();
String datumvan = jsonObject.optString("Start").toString();
String datumtot = jsonObject.optString("Einde").toString();
String leraar = jsonObject.optJSONArray("Docenten").optString("Naam").toString();
String inhoudles = jsonObject.optString("Inhoud").toString();
String datumvanconverted = datumvan.substring(0, 10);
DateFormat dateFormat = new SimpleDateFormat("HH:mm");
...
一切都有效,除了&#34; Leraar&#34;字符串,我希望有人可以帮助我。
-Z3r0byte
答案 0 :(得分:3)
这可能有效:
String leraar = jsonObject.optJSONArray("Docenten").getJSONObject(0).optString("Naam").toString();
所以Docenten
是一个JSONArray,可能需要使用索引访问它。
答案 1 :(得分:0)
我建议你创建一个带有相应字段的Item类,然后使用ObjectMapper将json解析为java Object。
private ObjectMapper mapper = new ObjectMapper();
Item item = mapper.readValue(input, new TypeReference<Item>(){});
item.getDocenten().get(0).getNaam();
和Item.class
public class Item {
// attributes
// constructor
// getter + setter
}
之后会更容易