我试图使用下面的代码创建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();
}
但它不起作用,结果为null,与JsonObject相同。我做错了什么?
EDIT。使用JsonProperties的结果类。这很奇怪,我试图创建JsonObcject作为Test的模拟
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;
}
}
答案 0 :(得分:0)
问题:我试图让JsonObject在测试中
没有testCompile 'org.json:json:20140107'
它是不可能的。