字符串到json转换问题

时间:2012-10-04 12:52:19

标签: java json

我正在尝试使用以下代码将字符串转换为JSONObject对象,但我正在

Exception in thread "main" java.lang.ClassCastException: 
org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject .

来源:

import net.sf.json.JSONObject;
import org.json.simple.parser.JSONParser;
    public static void run(JSONObject jsonObject) {
        System.out.println("in run--");

    }

    public static void main(String[] args) throws Exception {
        System.out.println("here");
        String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}";
        JSONObject jsonObj;
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(json);

        jsonObj = (JSONObject) obj;

        run(jsonObj);
    }

这里有什么问题?

2 个答案:

答案 0 :(得分:2)

您从错误的包中导入了JSONObject。改变这一行:

import net.sf.json.JSONObject;

到此:

import org.json.simple.JSONObject;

答案 1 :(得分:0)

实施以下解决方案 您甚至不必担心解析器 ......

这里的问题是你试图将org.json.simple.JSONObject类型的对象强制转换为net.sf.json.JSONObject。您可能想尝试包org.codehaus.jettison.json.JSONObject。这足以完成所有必需的事情。

简单示例

首先,准备一个字符串:

String jStr = "{\"name\":\"Fred\",\"Age\":27}";

现在,要解析String对象,U只需将String传递给JSONObject();构造函数方法

JSONObject jObj = new JSONObject(jStr);

应该这样做,瞧!你有一个JSONObject。 现在你可以随心所欲地玩它。

如此简单不是吗?

修订版的代码可能类似于

<击>

<击>
import net.sf.json.JSONObject;

<击>

import org.codehaus.jettison.json.JSONObject;
public static void run(JSONObject jsonObject) {
    System.out.println("in run-- "+jsonObject.getInt("person_id"));
}

public static void main(String[] args) throws Exception {
    System.out.println("here");
    String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}";
    JSONObject jsonObj = new JSONObject(json);
    run(jsonObj);
}

使用JSON,这是简单的SssOooooooo