Conversion of JSON objects to JSON strings, JSON strings to Java objects

Source: Internet
Author: User
Tags case statement string to json javascript array

I. Conversion of JSON objects to JSON strings

1.How the jquery plugin supports conversion :

$.parsejson (JSONSTR); Jquery.parsejson (JSONSTR), you can convert a JSON string into a JSON object

2. browser supported conversion Mode (FIREFOX,CHROME,OPERA,SAFARI,IE9,IE8) and other browsers:

Json.stringify (obj) converts the JSON to a string. Json.parse (String) to convert the string to JSON format;

var a={"name": "Tom", "Sex": "Male", "Age": "24"};
var b= ' {' name ': ' Mike ', ' sex ': ' Female ', ' age ': ' 29 '} ';
var atostr=json.stringify (a);
var btoobj=json.parse (b);
Alert (typeof (Atostr)); String
Alert (typeof (Btoobj));//object

3.how JavaScript supports conversion :
Eval (' (' + jsonstr + ') '); You can convert a JSON string to a JSON object, noting that you need to wrap a pair of parentheses outside the JSON character
Note: IE8 (compatibility mode), IE7 and IE6 can also use eval () to convert strings to JSON objects, but these methods are not recommended, which is unsafe for eval to execute an expression in a JSON string.

4.JSON Official Conversion Mode :
http://www.json.org/provides a json.js so that IE8 (compatibility mode), IE7 and IE6 can support JSON objects as well as their stringify () and Parse () methods;
Can get this JS on Https://github.com/douglascrockford/JSON-js, generally now use json2.js.

Ii. conversion of JSON strings to Java objects

1. Convert the list of Java objects to an array of JSON objects and move to a string

Jsonarray array = jsonarray.fromobject (list);
String jsonstr = array.tostring ();

2. Converting Java objects to JSON objects and converting them into strings

Jsonobject object = jsonobject.fromobject (user);
Log4jInit.ysulogger.debug (Object.ToString ());

3. Convert the JSON string to an array of Java objects
Jsonarray json = Jsonarray.fromobject (USERSTR);//userstr is a JSON string
List<user> users= (list<user>) jsonarray.tocollection (JSON, user.class);


4. Convert the JSON string to a Java object

Jsonobject jsonobject = Jsonobject.fromobject (JSONSTR);
User user= (user) Jsonobject.tobean (object,user.class);

Why do I need to add parentheses when I eval a JSON string?

When interacting with the server, we typically initiate an AJAX request, and the server returns a JSON string similar to the ' {x:1,y:1} ' structure, which we convert to a direct amount of the object for the convenience of the client processing.

This is a lot of time through an eval to achieve

var jsonstr = ' {x:1, y:1} ';
var jsonobj = eval (' (' + jsonstr + ') ');

If the eval does not add parentheses to the script error, this is why?

Because eval is an execution environment, when you do not use parentheses {x:1, y:1} is interpreted as a compound statement, {and} here is a delimiter that conforms to the statement, rather than a grammatical way of the object's direct amount we originally thought. Just as we usually write if (true) {x=1;} The curly braces here also act as compound statements.

The next x: is interpreted as a label, and case X in the usual SWICTH case statement is also a label, and other uses of the label can refer to the relevant information. The back 1 is treated as a digital direct quantity

An error occurred when Y was interpreted as a variable identifier and then continued parsing the colon after Y because it was not recognized. So if you write eval (' {x:1, y = 1} ') you won't get an error, because Y=1 can be identified, and the result of Eval after Y=1 is to return 1.

But why is it possible to add parentheses around, because the parentheses here indicate enforcement, and the whole ' (' + Jsonstr + ') is actually interpreted as an expression operation instead of a compound statement, so the curly braces {} In JSONSTR are recognized as the syntax of the object, of course.

When we're done, let's look at an example, if we write eval (' {x:1} '), does that make an error?

The answer is no, because although {x:1} is considered to be a compound statement, the x:1 is correct, as a label to identify, so the result returns 1, plainly, just let {...} The representation of the compound statement does not allow the parsing can not understand, such as {x:1, y=1,z=3} will not error, return the final result 3

For example:

JSON string:
var str1 = ' {' name ': ' cxh ', ' sex ': ' Man '} ';
JSON object:
var str2 = {"Name": "Cxh", "Sex": "Man"};

One, JSON string converted to JSON object

To use the above str1, you must first convert to a JSON object using the following method:

Convert from JSON string to JSON object

var obj = eval (' (' + str + ') ');

Or

var obj = Str.parsejson (); Convert from JSON string to JSON object

Or

var obj = json.parse (str); Convert from JSON string to JSON object

Then, you can read this:

Alert (Obj.name);

Alert (Obj.sex);

Special Note: If obj is originally a JSON object, then using the eval () function after conversion (even if multiple conversions) is a JSON object, but there is a problem with the Parsejson () function (throwing a syntax exception).

Second, the JSON object can be converted to a JSON string using tojsonstring () or global Method Json.stringify ().

For example:

var last=obj.tojsonstring (); Convert a JSON object to a JSON character

Or

var last=json.stringify (obj); Convert a JSON object to a JSON character

alert (last);

Attention:

In the above several methods, in addition to the eval () function is JS own, the other several methods are from the Json.js package. The new version of JSON modifies the API to inject json.stringify () and Json.parse () two methods into the Javascript built-in object, which becomes the object.tojsonstring (), and the latter becomes the Strin G.parsejson (). If you are prompted not to find the tojsonstring () and Parsejson () methods, your JSON package version is too low.

Use of the Eval () function and the JSON object to the JSON string

Definition and usage

The eval () function computes a string and executes the JavaScript code in it.

Grammar

Eval (String): If the argument is an expression, the eval () function executes the expression. If the parameter is a JavaScript statement, Eval () executes the JavaScript statement.
Instance

eval("x=10;y=20;document.write(x*y)") document.write(eval("2+2")) var x=10 document.write(eval(x+17))输出:200427
    • 1
    • 2
    • 3
    • 4
    • 5
Eval Parse JSON object

var dataobj=eval ("(" +data+ ")");//Convert a JSON object to a JavaScript object
Such as:
V

ar txt = ‘{ “employees” : [’ +‘{ “firstName”:”Bill” , “lastName”:”Gates” },’ +‘{ “firstName”:”George” , “lastName”:”Bush” },’ +‘{ “firstName”:”Thomas” , “lastName”:”Carter” } ]}’;//为json对象
    • 1
    • 2
    • 3
    • 4

var obj = eval ("(" + txt + ")");//converted to JavaScript array object;
Note: Why should eval be added here to "(" ("+data+");//" ?

The reason is that eval itself is a problem. Since JSON starts and ends in the form of "{}", in JS, it is treated as a block of statements, so it must be coerced into an expression.
The purpose of the parentheses is to force the Eval function to force the expression in parentheses to be converted to an object while processing the JavaScript code, rather than being executed as a statement (statement). For example, if the object literal {} is not enclosed, then eval will recognize the curly brace as the start and end tag of the JavaScript block, and {} will be considered an empty statement. So the following two execution results are different:

alert(eval(“{}”); // return undefinedalert(eval(“({})”);// return object[Object]
    • 1
    • 2

For this kind of writing, in JS, you can see everywhere.
such as: (function ()) {} (); Do the closure operation and so on.

Browser-supported conversion modes (FIREFOX,CHROME,OPERA,SAFARI,IE9,IE8) and other browsers:

Json.parse (JSONSTR); You can convert a JSON string into a JSON object
Json.stringify (Jsonobj); You can convert a JSON object to a JSON string

How the jquery plugin supports conversion:

$.parsejson (JSONSTR); Jquery.parsejson (JSONSTR), you can convert a JSON string into a JSON object

Conversion of JSON objects to JSON strings, JSON strings to Java objects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.