Java 如何将文件转换为JSON中可接受的字符串?
我试图通过REST ASSURED在Github中创建GIST 要创建摘要,需要传递文件名及其内容 现在,文件的内容被API拒绝了 例如:Java 如何将文件转换为JSON中可接受的字符串?,java,json,Java,Json,我试图通过REST ASSURED在Github中创建GIST 要创建摘要,需要传递文件名及其内容 现在,文件的内容被API拒绝了 例如: { "description": "Hello World Examples", "public": true, "files": { "hello_world.rb": { "content": "class HelloWorld\n def initialize(name)\n @name
{
"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"
}
}
这就是API想要JSON的样子,我可以通过我的代码得到:
{
"description": "Happy World",
"public": true,
"files": {
"sid.java": {
"content": "Ce4z5e22ta"
},
"siddharth.py": {
"content": "def a:
if sidh>kundu:
sid==kundu
else:
kundu==sid
"
}
}
}
因此,缩进的变化导致GitHUb API失败,出现400个错误。有人能帮忙吗?正如评论中指出的,JSON不允许字符串中包含控制字符。在换行的情况下,在示例中,这些换行被编码为
\n
你当然应该考虑使用适当的库来创建JSON,而不是自己处理原始字符串。
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库
非常确定JSON不允许多行字符串。您似乎是通过连接字符串部分来生成JSON。不要这样做。使用实际的JSON库来生成JSON节点,或者更好地将对象映射到JSON。JSON库将通过转义所有需要转义的内容来生成有效的JSON。您缺少最后一个结束括号在您的第一个代码段中,这是故意的吗?因为这不是一个有效的JSON文本。