tags:

views:

1952

answers:

3

I want to create a JSON object. I have tried the following

myString=new JSONObject().put("JSON", sampleClass).toString();

but mystring gives me {"SampleClass@170f98"}.

I also tried the following

 XStream xsStream=new XStream(new JsonHierarchicalStreamDriver());
 SampleClass sampleClass=new SampleClass(userset.getId(),userset.getUsername());
 myString=xsStream.toXML(sampleClass);

It works but when i use getJSON in javascript to get myString it does not work.

A: 

You should try:

XStream xsStream=new XStream(new JettisonMappedXmlDriver());
Kees de Kooter
+1  A: 

try

String myString = new JSONObject().put("JSON", new JSONObject(sampleClass)).toString();

in my instance it looks like this:

import org.json.JSONObject;
import org.junit.Test;

public class JsonTest
{
    public static class SampleClass
    {
        private String id;

        private String userName;

        public SampleClass ( String id, String name )
        {
            this.id = id;
            this.userName = name;
        }

        public String getUserName ()
        {
            return userName;
        }

        public void setUserName ( String userName )
        {
            this.userName = userName;
        }

        public String getId ()
        {
            return id;
        }

        public void setId ( String id )
        {
            this.id = id;
        }
    }

    @Test
    public void testSampleClass () throws Exception
    {
        SampleClass sampleClass = new SampleClass ( "myId", "MyName" );
        System.out.println ( new JSONObject ( sampleClass ).toString () );
    }
}

the result looks like this:

{"userName":"MyName","id":"myId"}
Mauli
The Constructor JSONObject(sampleClass) is undefined
Jugal
I am getting the following errorA JSONObject text must begin with '{' at character 1 of SampleClass@1385846please help me to solve
Jugal
no it isn't http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject(java.lang.Object)
Mauli
you are sure that your toString() call is at the right place? Please post more of your code, in any other case it is just guessing.
Mauli
ok Thanks. i am trying so please wait for a moment
Jugal
Thanks its working now but how to use it in JSP page. iam using getJSON in javascript but not working.
Jugal
A: 

Look into GSON, a Java Library for converting Objects to JSON by Google. GSON Library

From the Google Code site:

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
Derp Developer