简体   繁体   English

我们如何使用 gson.JsonObject 在非静态 java 方法/类中创建 Json

[英]How do we create a Json in a non-static java method/class using gson.JsonObject

Unable to create a JsonObject in a java class, giving syntax error:无法在 java class 中创建 JsonObject,出现语法错误: 在此处输入图像描述

you are trying to put code in a invalid body part of the class.您试图将代码放入 class 的无效正文部分。

You have to add a method or a constructor to the class example:您必须向 class 示例添加方法或构造函数:

public class FileRequestJson {

    JsonObject file = new JsonObject();

    public  FileRequestJson() {
        file.addProperty("", "");
    }

    public JsonObject newMethod(JsonObject newfile){
        newfile.addProperty("", "");
        return newfile;
    }
}

I think you are new to coding.我认为您是编码新手。 You should write the code within the method.您应该在方法中编写代码。 The following code might help you.以下代码可能会对您有所帮助。

    import com.google.gson.JsonObject;

  public class JsonFromGson {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    JsonFromGson  json =new JsonFromGson();
    json.createJson();
}

public void createJson() {

    JsonObject file = new JsonObject();
    file.addProperty("Name", "Jyo");
    file.addProperty("age", 23);
    System.out.print(file);
}

} }

Like @Robby Cornelissen said就像@Robby Cornelissen 说的

Code needs to be inside a method or initializer block代码需要在方法或初始化块中

Perhaps you meant to have也许你本来打算

import com.google.gson.JsonObject;

class FileRequestJson extends JsonObject {
    {
        addProperty("Name", "Jyo");
        addProperty("age", 23);
    }
}

or how I like is...或者我喜欢的是...

import org.json.JSONObject;

class AClass {
    public void method() {

        JSONObject fileRequest = new JSONObject() {{
            put("Name", "Jyo");
            put("age", 23);
        }};

        System.out.println(fileRequest.toString(2));
    }
}

Both of these options use non-static block construction which may be considered a little bad practice by some people.这两个选项都使用非静态块构造,这可能被某些人认为是一种不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM