我的Json属于以下类型:
{
"result": [
{
"skills": "alexa",
"brand": "amazon",
"name": "jack",
"type": "noob",
"id": "1230",
"date": "8-5-2016"
}
]
}
我想从这个json获取名称和id。我尝试使用简单的json和gson nut,当我尝试2级时,即访问“name”变量我得到一个空引用指针错误。
另请注意,我是从URL获取此内容。 谢谢!!
我的Java代码是
JSONObject obj1= new JSONObject(line);
JSONArray cobj = (JSONArray)obj1.getJSONArray("result");
JSONObject ccobj = (JSONObject)cobj.get(1);
System.err.println(ccobj.getString("result"));
答案 0 :(得分:1)
你的json无效。
interface IArray {
public void add(Object element);
public void addAll(Object elements[]);
}
...
Array implements IArray {...}
ArrayCount implements IArray {...}
一旦你纠正了我建议使用Gson。
答案 1 :(得分:0)
创建这些类
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
@SerializedName("result")
@Expose
private List<Result> result = new ArrayList<Result>();
/**
*
* @return
* The result
*/
public List<Result> getResult() {
return result;
}
/**
*
* @param result
* The result
*/
public void setResult(List<Result> result) {
this.result = result;
}
}
-----------------------------------com.example.Result.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Result {
@SerializedName("skills")
@Expose
private String skills;
@SerializedName("brand")
@Expose
private String brand;
@SerializedName("name")
@Expose
private String name;
@SerializedName("type")
@Expose
private String type;
@SerializedName("id")
@Expose
private String id;
@SerializedName("date")
@Expose
private String date;
/**
*
* @return
* The skills
*/
public String getSkills() {
return skills;
}
/**
*
* @param skills
* The skills
*/
public void setSkills(String skills) {
this.skills = skills;
}
/**
*
* @return
* The brand
*/
public String getBrand() {
return brand;
}
/**
*
* @param brand
* The brand
*/
public void setBrand(String brand) {
this.brand = brand;
}
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return
* The type
*/
public String getType() {
return type;
}
/**
*
* @param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* @return
* The id
*/
public String getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* @return
* The date
*/
public String getDate() {
return date;
}
/**
*
* @param date
* The date
*/
public void setDate(String date) {
this.date = date;
}
}
然后你会做这样的事情
Gson gson = new Gson();
Example ex = gson.fromJson(jsonString,Example.class);
然后从示例对象中获取结果,迭代,拉出你想要的任何内容。