pars
pars

Reputation: 151

String to json conversion issue

I am trying to convert a string to JSONObject object using the below code,but i am getting

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

Source:

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);
    }

What is wrong here?

Upvotes: 2

Views: 12194

Answers (2)

Nokia808Freak
Nokia808Freak

Reputation: 921

Implementing the following solution, You don't even have to bother about a parser...

The Problem here is that u're trying to cast a object of type org.json.simple.JSONObject to net.sf.json.JSONObject. You might wanna try The package org.codehaus.jettison.json.JSONObject. that is enough to do all the required things.

Simple Example:

First, Prepare a String:

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

Now, to parse the String Object, U just have to pass the String to the JSONObject(); constructor method

JSONObject jObj = new JSONObject(jStr);

That should do it and voila! You have a JSONObject. Now you can play with it as u please.

How So Simple ain't it?

The Modified version of the Code might look like:

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);
}

with JSON, It's SssOooooooo simple

Upvotes: 0

David Grant
David Grant

Reputation: 14223

You've imported JSONObject from the wrong package. Change this line:

import net.sf.json.JSONObject;

to this:

import org.json.simple.JSONObject;

Upvotes: 2

Related Questions