使用json.org解析时出现JSON错误

时间:2014-02-28 15:57:00

标签: java json parsing

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException, ParseException {


        String s = "{paramsArray: [\"first\", 100],"
                + "paramsObj: {one: \"two\", three: \"four\"},"
                + "paramsStr: \"some string\"}";

        JSONParser parser = new JSONParser();
        Object ob = parser.parse(s);
        JSONObject obj = (JSONObject) ob;
        System.out.println(obj.get("paramsStr"));


    }

}

Error: Exception in thread "main" Unexpected character (p) at position 1.
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at Main.main(Main.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) `

2 个答案:

答案 0 :(得分:2)

你的json无效。

paramsArrayparamsObjonethreeparamsStr应该用双引号括起来(有效的JSON包含密钥和值)

String s = "{\"paramsArray\": [\"first\", 100],"
            + "\"paramsObj\": {\"one\": \"two\", \"three\": \"four\"},"
            + "\"paramsStr\": \"some string\"}";

尝试使用JSONLint等JSON验证程序。

答案 1 :(得分:1)

"{ 'paramsArray': ['first', '100']," + 
  "'paramsObj': { 'one':   'two'," +
                   "'three': 'four'}," +
  "'paramsStr': 'some string'}"

在double中使用单引号可以提高可读性......