我有一个像这样的字符串
[{"id":"id","name":"","age":"","desig":"salary","dept":""}],
[{"id":"id","name":"","age":"","desig":"salary","dept":""}],[],[],
[],,,,,,ABC,ABC,XYZ,false,Hello
我想将其转换为JSONArray
。当我试图转换时,我只得到值
{"id":"id","name":"","age":"","desig":"salary","dept":""}
在那个数组中。我没有得到其他价值观。
答案 0 :(得分:1)
您拥有的数据无效JSON,因为它采用以下格式:
x,y,z
...即使x
,y
和z
都是JSON数组,实际的字符串本身也不是JSON数组。 JSONArray
只需要进行解析,阅读它认为有效的JSON,然后停止解析。
您需要将数据放入有效的JSON格式:
[x,y,z]
然后你可以用JSONArray
解析它。如果你的输入总是这个无效的JSON,你可以这样纠正它:
JSONArray ja = (JSONArray) JSONSerializer.toJSON("[" + badJsonString + "]");
编辑:您使用的是4-year old, no-longer-supported fork of the original json.org Java library而不是the supported, up to date, original json.org Java library,因此我已将代码段更改为匹配。
编辑:查看您的数据,即使在数组之后它也不是有效的JSON数据。你有:
valid JSON array,
valid JSON array,empty valid JSON array,,empty valid JSON array,
empty valid JSON array,no data,no data,no data,no data,no data,text without quotes,text without quotes,text without quotes,text without quotes
任何JSON解析器都无法解析此问题。如果您的数据确实采用这种格式,则需要将JSON解析器与您自己的解析器结合使用,例如
while (stillDataToRead) {
if (nextChar == '[') {
parseJSONArrayAndAdvanceTheCursor();
ignoreCommaAndAdvanceTheCursor();
}
else if (nextChar == ',') {
recordABlankField();
}
else {
readAnUnquotedStringUpToTheNextComma();
}
}
或者......以正确的JSON格式获取数据!
[[{"id":"id","name":"","age":"","desig":"salary","dept":""}],
[{"id":"id","name":"","age":"","desig":"salary","dept":""}],[],[],
[],null,null,null,null,null,"ABC","ABC","XYZ",false,"Hello"]
答案 1 :(得分:0)
你的String不是有效的JSONArray。感谢json.org JSONArray以[
开头并以]
结束,就像你的第一行一样。因此,解析器会将第一行视为数组,并在第一行]
之后停止解析。
如果您想将完整的字符串用作arry,请将[
和]
括起来,然后重试:
[[{"id":"id","name":"","age":"","desig":"salary","dept":""}],
[{"id":"id","name":"","age":"","desig":"salary","dept":""}],[],[],
[],,,,,,ABC,ABC,XYZ,false,Hello]
答案 2 :(得分:0)
JsonFactory factory = new JsonFactory();
JsonGenerator generator;
// Create a StringWriter instance to buffer the JSON data.
Writer outWriter = new StringWriter();
try{
// Create a JSON generator backed by the StringWriter instance created above.
generator = factory.createGenerator(outWriter);
generator.writeStartObject();
generator.writeStartArray();
generator.writeStringField("id","id");
generator.writeStringField("name", "");
generator.writeStringField("age", "age");
generator.writeStringField("desig","salary");
generator.writeStringField("dept","");
// end writting }
generator.writeEndArray();
generator.writeEndObject();
generator.close();
// System.out.println(outWriter.toString());
}catch(JsonGenerationException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println(outWriter.toString());
试试这个以获得数组&取决于您的需求变化&用它 为此你必须使用杰克逊图书馆