Java:正在生成 JSON:尝试命名 object 和数组时出现异常
Java: Generating JSON: Getting exception when try to name object & array
我正在尝试生成 JSON 结构如下:
"rows": [
{
"object": {
"id": "1"
},
"values": [
"111",
"reg text",
"11"
]
}
]
这是代码:
.writeStartObject()
.writeStartArray("rows")
.writeStartObject() //here i can`t name the object
.write("id", "'1'@1000")
.writeEnd()
.writeStartArray() //here i can`t name the array
.write("fax")
.write("646 555-4567")
.writeEnd()
.writeEnd()
.writeEnd();
当我尝试在括号内添加 object 和数组 headers 时,出现异常 "Illegal method during JSON generation, not valid in current context IN_ARRAY"。
如何像我一样生成JSON?
此代码在您的问题中产生 JSON 输出:
generator.writeStartObject()
.writeStartArray("rows")
.writeStartObject()
.writeStartObject("object")
.write("id", "1")
.writeEnd()
.writeStartArray("values")
.write("111")
.write("reg text")
.write("11")
.writeEnd()
.writeEnd()
.writeEnd()
.writeEnd();
第一个 writeStartObject
开始了 rows
数组中的匿名对象。第二个 writeStartObject
产生:
"object": {
[...]
}
关于您的评论:
.writeStartObject() //here i can`t name the object
[...]
.writeStartArray() //here i can`t name the array
您不能指定名称,因为对象和数组都是数组中的值。关键是把它们都封装在一个对象里,然后它们都可以(其实必须)都有名字
我正在尝试生成 JSON 结构如下:
"rows": [
{
"object": {
"id": "1"
},
"values": [
"111",
"reg text",
"11"
]
}
]
这是代码:
.writeStartObject()
.writeStartArray("rows")
.writeStartObject() //here i can`t name the object
.write("id", "'1'@1000")
.writeEnd()
.writeStartArray() //here i can`t name the array
.write("fax")
.write("646 555-4567")
.writeEnd()
.writeEnd()
.writeEnd();
当我尝试在括号内添加 object 和数组 headers 时,出现异常 "Illegal method during JSON generation, not valid in current context IN_ARRAY"。 如何像我一样生成JSON?
此代码在您的问题中产生 JSON 输出:
generator.writeStartObject()
.writeStartArray("rows")
.writeStartObject()
.writeStartObject("object")
.write("id", "1")
.writeEnd()
.writeStartArray("values")
.write("111")
.write("reg text")
.write("11")
.writeEnd()
.writeEnd()
.writeEnd()
.writeEnd();
第一个 writeStartObject
开始了 rows
数组中的匿名对象。第二个 writeStartObject
产生:
"object": {
[...]
}
关于您的评论:
.writeStartObject() //here i can`t name the object
[...]
.writeStartArray() //here i can`t name the array
您不能指定名称,因为对象和数组都是数组中的值。关键是把它们都封装在一个对象里,然后它们都可以(其实必须)都有名字