我在stackoverflow上也看到了同样的问题,它讲述了Json中的多余逗号和空格。但这并没有帮助我。
我在POJO中有这种格式的json
{"binary":[
{
"attributeIndex": 4,
"attributeValue": "no",
"binaryValue": "1,0"
},
{
"attributeIndex": 4,
"attributeValue": "yes",
"binaryValue": "0,1"
}
]}
POJO
public class BinPojo {
/**
* @param args
*/
int attributeIndex;
String attributeValue;
String binaryValue;
and
public class BinaryPojo {
/**
* @param args
*/
JSONArray binary;
我正在尝试获取attributeIndex,attributeValue,binaryValue值,但出现此错误
Caused by: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected ':' at line 1 column 65
at com.google.gson.Gson.fromJson(Gson.java:818)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
在
BinPojo getData = gson.fromJson(meta.get(j).toString(), BinPojo.class);
我的代码:
JSONArray meta = new JSONArray();
//file read
String setupData = bf.readLine();
BinaryPojo d = gson.fromJson(setupData, BinaryPojo.class);
meta = d.getBinary();
//JSONArray meta which holds the JSON data
for (int j = 0; j < meta.size(); j++) {
BinPojo getData = gson.fromJson(meta.get(j).toString(), BinPojo.class);
System.out.println("gson"+gson.toJson(getData));
int attrIndex = getData.getAttributeIndex();
System.out.println("attrIndex: "+attrIndex);
String attrVal = getData.getAttributeValue();
}
可能是什么原因。这说明我的JSON不好,我该如何调试。
编辑
一旦我打印此:
System.out.println("meta: "+meta.get(j).toString());
我的结果是
meta:{attributeIndex = 0.0,attributeValue = Middleaged,binaryValue = 1,0,0}
和
for (int j = 0; j < meta.size(); j++) {
System.out.println("meta: "+meta.get(j).toString());
BinPojo getData = null ;
try{
getData = gson.fromJson(meta.get(j).toString(), BinPojo.class);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("gson "+gson.toJson(getData));
int attrIndex = getData.getAttributeIndex();
System.out.println("attrIndex: "+attrIndex);
String attrVal = getData.getAttributeValue();
}
getData返回null。
gson null
java.lang.Exception: java.lang.NullPointerException
at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:354)
Caused by: java.lang.NullPointerException
啊! 我认为那是你的问题。您使用的是“ JSON-简单”库(org.json.simple.*
),而不是“ JSON for Java”库(org.json.*
)。他们都有名为的类JSONArray
。但是org.json.simple.JSONArray
from JSON-Simple不会toString()
像org.json.JSONArray
从“ JSON for Java”那样从其方法返回JSON 。
您需要toJSONString()
改为在JSONArray
和JSONObject
对象上使用。
请密切注意您实际使用的库。在您的问题中包括它们(最好带有版本号)将使回答这样的问题变得更加容易。类名称在项目中不是唯一的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句