【发布时间】:2016-10-07 22:08:17
【问题描述】:
我正在处理一项实验室任务,在第一部分中,我需要实现一个简单的 JSON 库,以便可以在 Java 中导出 JSON 数据。
现在我被 JSONobject toString() 函数困住了;
该库应该可以将 JSON 模型导出为文本表示形式,以便将其存储在文件中,或使用 HTTP 传输,因此我需要使用 toString 方法
但是我已经遇到了错误,有人可以帮助我使用 toString 函数
这是我的 JsonObject 类:
import java.util.LinkedHashMap;
public class JsonObject extends LinkedHashMap<String, JsonValue> implements JsonValue {
@Override
public JsonObject asObject(){
return this;
}
public void put(String key, int i){
JsonPrimitive jsonprim = new JsonPrimitive(i);
this.put(key, jsonprim);
}
public void put(String key, boolean b){
JsonPrimitive jsonprim = new JsonPrimitive(b);
this.put(key, jsonprim);
}
public void put(String key, double d){
JsonPrimitive jsonprim = new JsonPrimitive(d);
this.put(key, jsonprim);
}
public void put(String key, String string){
JsonPrimitive jsonprim = new JsonPrimitive(string);
this.put(key, jsonprim);
}
public JsonValue get(String key){
throw new UnsupportedOperationException(
"Cannot return JsonValue of type " + this.getClass().getSimpleName() + "as string");
}
public boolean has(String key) {
throw new UnsupportedOperationException(
"Cannot return JsonValue of type " + this.getClass().getSimpleName() + "as string");
}
public JsonValue get(int index) {
return this.get(index);
}
这是我卡住的 toString
public String toString() {
return this.toString();
}
}
&主要方法
public static void main(String[] args) {
//Create a nested JSON object containing user records
JsonArray userRecords = new JsonArray();
userRecords.add(new JsonObjectBuilder()
.add("id", 1)
.add("name", "John Doe")
.add("address", new JsonObjectBuilder()
.add("street", "Abbey Road")
.add("number", 7)
.add("city", "London"))
.build());
userRecords.add(new JsonObjectBuilder()
.add("id", 2)
.add("name", "Jane Doe")
.add("address", new JsonObjectBuilder()
.add("street", "Abbey Road")
.add("number", 8)
.add("city", "London"))
.build());
//Print the records
System.out.println(userRecords);
//Retrieve the address of the first user
System.out.println(userRecords.get(0).get("address"));
【问题讨论】:
-
您遇到什么错误?实际结果是什么?您的预期是什么?
-
我应该得到我在 main 中硬编码的记录的 json 代码,但我可以构建项目