convert string to json object


To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript’s syntax.

var myObject = eval(‘(‘ + myJSONtext + ‘)’);

However JSON.parse is still recommended:

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

var myObject = JSON.parse(myJSONtext, reviver);

in java Convert object to json

Using Gson is easy to do the conversion:

In my case, I just need to do simple string without nested object. So i just use Map in java. We can also passing complex object directly into the gson parser.

 @RequestMapping(value = "/reviewEligibility/{dealId}", method = RequestMethod.GET)
    public String reviewEligibility(@PathVariable("dealId") String dealId) throws Exception {
        boolean isExpeditedEligible =  xxServices.checkExpeditedReviewEligibility(Long.parseLong(dealId));
        boolean isLimitedEligible =  xxServices.checkLimitedReviewEligibility(Long.parseLong(dealId));

        Map<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("Expedited", String.valueOf(isExpeditedEligible));
        resultMap.put("Limited", String.valueOf(isLimitedEligible));
        Gson gson = new Gson();
        String result = gson.toJson(resultMap);
        return result;

the rest service would return me : {“Expedited”:”false”,”Limited”:”false”}


One comment

  1. SutoCom · August 14, 2013

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s