我写了这个JSON代码
public class TestClass {
public static void main(String[] args) {
String inputJson= "{" +"\"contexts\" : { "+ "{ " + "\"times\" : { " + "{ " + "\"end\":17, " + "\"begin\" : 9 " + "}" + "}," + "\"contextname\":\"OFFICE_HOURS\" " + "}," + "{ " + "\"days\": { " + "\"MON\", " + "\"TUE\", " + "\"WED\" , " + "\"THU\", " + "\"FRI\" " + "} , " + "\"contextname\" : \"WORKDAYS\" " + "}";
ObjectMapper mapper= new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
try {
MainParser mp= mapper.readValue(inputJson, MainParser.class);
System.out.println(mp.getContextname());
}
但是我在控制台框中发现了此错误
org.codehaus.jackson.JsonParseException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
at [Source: java.io.StringReader@7cf10a6f; line: 1, column: 19]
我需要帮助
答案 0 :(得分:2)
格式化后,您的JSON如下所示:
{
"contexts": {
{
"times": {
{
"end": 17,
"begin": 9
}
},
"contextname": "OFFICE_HOURS"
},
{
"days": {
"MON",
"TUE",
"WED",
"THU",
"FRI"
},
"contextname": "WORKDAYS"
}
这是无效的,有多种原因。
通过使用数组替换“上下文”的内容并将日期包装在数组中,并删除一些多余的花括号,可以使其生效。
{
"contexts": [
{
"times": {
"end": 17,
"begin": 9
},
"contextname": "OFFICE_HOURS"
},
{
"days": [
"MON",
"TUE",
"WED",
"THU",
"FRI"
],
"contextname": "WORKDAYS"
}
]
}
更好的方法可能是使用“ contextname”值作为键并简化整个JSON。
{
"OFFICE_HOURS": {
"end": 17,
"begin": 9
},
"WORKDAYS": [
"MON",
"TUE",
"WED",
"THU",
"FRI"
]
}
答案 1 :(得分:0)
以下是根据代码的Json字符串。它不是正确的json格式。
{“ contexts”:{{“ times”:{{“ end”:17,“ begin”:9}},“ contextname”:“ OFFICE_HOURS”},{“ days”:{“ MON”,“ TUE”,“ WED”,“ THU”,“ FRI”},“ contextname”:“ WORKDAYS”}
尝试修复json字符串格式,然后再次运行代码。