Ganesh R
Ganesh R

Reputation: 61

How to convert String values to json object in java without using org.json

I'm trying to convert a JSON String value `{"name:ganesh,sex:male,age:22"} ) into key and value set using json in gwt can anyone help me with some ideas please.

Upvotes: 1

Views: 1995

Answers (2)

Blessed Geek
Blessed Geek

Reputation: 21654

Your string must be of the form

"{'name':'ganesh','sex':'male','age':'22'}"

or '{"name":"ganesh","sex":"male","age":"22"}'

You can use one of the following ways ...

  • Use javascript eval. Embed the eval in JSNI

    public static native String eatString(String jstring) /*-{
      eval("var hello = " + jstring + ";");
      return hello;
    }-*/;
    
  • Pass the String as script in a JSP GWT hosting file. This way, you can only doing once - when the GWT app is loaded with its hosting file. Your JSP will generate the javascript dynamically for each loading.

    Place the following in hour GWT hosting html file, before the script tag where GWT module is called.

    <script>
    var hello = {'name':'ganesh','sex':'male','age':'22'};
    </script>
    

    Then in your GWT app, use the GWT Dictionary class to reference any javascript objects declared in the hosting file.

  • Use the following utilities, in particular JsonRemoteScriptCall.java to read remote, out of SLD-SOP javascript objects into your GWT app. http://code.google.com/p/synthfuljava/source/browse/trunk/gwt/jsElements/org/synthful/gwt/javascript/#javascript%2Fclient.

    Please be warned - out of SLD-SOP objects can be hazardous. Read up on Second level domain, same origin policy browser security.

  • Use RestyGWT and pretend that the data from the server comforms to REST data structure. But of course, use of json.org and google JSON utils has already been done for you.

Upvotes: 2

Noah
Noah

Reputation: 582

Since you don't want to use org.json, I imagine that you need to convert JSON on the client side. If this is the case, you will need to use GWT's JSON libraries. They could be inherited into your GWT project by adding these lines to your .gwt.xml file:

<inherits name="com.google.gwt.json.JSON" />  
<inherits name="com.google.gwt.http.HTTP" />

You'll also need to import the com.google.gwt.json packages into your class files.

The getting started guide to using JSON in GWT can be found here. It also provides examples for decoding JSON.

Upvotes: 2

Related Questions