实现 JSON 库 Java - ToString 函数

Implementing JSON Library Java - ToString function

我正在做实验作业,第一部分我需要实现一个简单的 JSON 库,这样我就可以在 Java 中导出 JSON 数据。

现在我卡在了 JSONobject toString() 函数上;

库应该可以将 JSON 模型导出为文本表示,以便可以将其存储在文件中,或使用 HTTP 传输,因此我需要使用 toString 方法

但是我已经遇到错误,有人可以帮助我使用 toString 函数

这是我的 JsonObject class :

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"));

你的错误是"java.lang.WhosebugError"吗?

如果是这样,您的 toString() 方法就是原因。你正在写

public String toString() {
      return this.toString();
  }
}

应该是这样的

public String toString() {
      return super.toString();
  }
}

或其他一些实现。 (至少,不要调用 this.toString())

因为 "this" 这里指向你的 JsonObject class 而 this.toString() 就是这个方法本身。

因此在 toString() 方法中调用 this.toString() 会导致无限方法调用。