【发布时间】:2017-04-12 11:28:51
【问题描述】:
我正在尝试使用下面的代码创建 JsonObcject
try {
JSONObject object = new JSONObject();
object.put("count", 39);
JSONArray results = new JSONArray();
JSONObject resultsAll = new JSONObject();
resultsAll.put("id", 2);
resultsAll.put("name", "PlaylistExample");
resultsAll.put("owned_by", 4);
resultsAll.put("votes_per_day", 25);
resultsAll.put("is_subscribed", true);
results.put(resultsAll);
object.put("results", results);
JSONArray finalArray = object.getJSONArray("results");
JSONObject finalObject = finalArray.getJSONObject(0);
result = new Results(finalObject);
} catch (JSONException e) {
e.printStackTrace();
}
但它不起作用,结果为空,与 JsonObject 相同。我做错了什么?
编辑。带有 JsonProperties 的结果类。这很奇怪,我试图创建 JsonObcject 作为测试的模拟
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.json.JSONException;
import org.json.JSONObject;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Results {
@JsonProperty("id")
private int id;
@JsonProperty("name")
private String name;
@JsonProperty("owned_by")
private int owned_by;
@JsonProperty("votes_per_day")
private int votes_per_day;
@JsonProperty("tracks_to_play")
private int tracks_to_play;
@JsonProperty("is_subscribed")
private boolean is_subscribed;
public Results(JSONObject object) {
try {
this.id = object.getInt("id");
this.name = object.getString("name");
this.owned_by = object.getInt("owned_by");
this.votes_per_day = object.getInt("votes_per_day");
this.tracks_to_play = object.getInt("tracks_to_play");
this.is_subscribed = object.getBoolean("is_subscribed");
} catch (JSONException ex) {
ex.printStackTrace();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getOwned_by() {
return owned_by;
}
public void setOwned_by(int owned_by) {
this.owned_by = owned_by;
}
public int getVotes_per_day() {
return votes_per_day;
}
public void setVotes_per_day(int votes_per_day) {
this.votes_per_day = votes_per_day;
}
public int getTracks_to_play() {
return tracks_to_play;
}
public void setTracks_to_play(int tracks_to_play) {
this.tracks_to_play = tracks_to_play;
}
public boolean is_subscribed() {
return is_subscribed;
}
public void setIs_subscribed(boolean is_subscribed) {
this.is_subscribed = is_subscribed;
}
}
【问题讨论】:
-
你能告诉我们
Results类的代码吗?是你自己的课还是某个图书馆的课? -
当然,请稍等
-
另外,您如何访问
JSONObject object并获得空值?在上面的代码中,这似乎是不可能的,因为你写了JSONObject object = new JSONObject();并且你永远不会重新分配它。 -
我做了断点
标签: java json string parsing object