Sachin Jain
Sachin Jain
Branch Unspecified
05 Feb 2012

JSON object to string

Hey guys,
I need to convert a JSON object to string using java program.
And then i will receive that string in a javascript code.
So please tell me how to convert JSON object to string in java
And then how to convert received object which is string back to JSON object.

PS:I am beginner in javascript coding and I have already searched on google.
06 Feb 2012
Try this out:
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};
 
var tmp = {one: 1, two: "2"};
JSON.stringify(tmp); // '{"one":1,"two":"2"}'

Share this content on your social channels -

Only logged in users can reply.