如何将文件转换为JSON接受的字符串?

时间:2018-11-23 14:24:42

标签: java json

我正在尝试通过REST ASSURED在Github中创建要点。

要创建要点,需要传递文件名及其内容。

现在,文件的内容已被API拒绝。

示例:

"Failed to resolve: org.jetbrains.kotlin:kotlin-stdlib-jre7..."

这是API想要JSON的方式,我可以通过我的代码获得它:

{
    "description": "Hello World Examples",
    "public": true,
    "files": {
        "hello_world.rb": {
            "content": "class HelloWorld\n def initialize(name)\n @name = name.capitalize\n end\n def sayHi\n puts \"Hello !\"\n end\nend\n\nhello = HelloWorld.new(\"World\")\nhello.sayHi"
        },
        "hello_world.py": {
            "content": "class HelloWorld:\n\n def init(self, name):\n self.name = name.capitalize()\n \n def sayHi(self):\n print \"Hello \" + self.name + \"!\"\n\nhello = HelloWorld(\"world\")\nhello.sayHi()"
        },
        "hello_world_ruby.txt": {
            "content": "Run ruby hello_world.rb to print Hello World"
        },
        "hello_world_python.txt": {
            "content": "Run python hello_world.py to print Hello World"
        }
    }

因此,缩进的更改导致GitHUb API失败,并显示400错误。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

如注释中所指出,JSON不允许字符串中包含控制字符。在换行符的情况下,在示例中将其编码为\n

您绝对应该考虑使用适当的库来创建JSON,而不是自己处理原始字符串。

答案 1 :(得分:0)

  1. 创建一个表示您要点的POJO(即具有诸如'description','files'集合之类的字段的对象。并为包含字符串字段'name'和'content'的文件单独设置POJO;
  2. 执行以下操作以转换您的要旨:

    try {
        GistFile file new GistFile();// Assuming this is POJO for your file
        //Set name and content
        Gist gist = new Gist(); //Asuming this is a POJO for your gist
        gist.addFile(file);
        //Add more files if needed and set other properties
        ObjectMapper mapper = new ObjectMapper();
        String content = mapper.writeValueAsString(gist);
        //Now you have valid JSON string
    } catch (Exception e) {
        e.printStackTrace();
    }
    

这用于com.fasterxml.jackson.databind.ObjectMapper或使用其他JSON库

  1. 实际上,有特定于GitHub的库可以为您完成大部分工作。请参考以下问题:How to connect to github using Java Program可能会有帮助