An error occurs when JSON. parse is used to convert a json string to a json object. json. parsejson
If the data obtained from the database (especially the description information) contains special characters, JSON is used. an error occurs when parse converts a json string to a json object, mainly because of double quotation marks and carriage return. The left angle brackets and right angle brackets also cause display problems, therefore, some special characters must be encoded or escaped before the json object is converted to the output page. The following shows the C # code encoding and escape common special characters. After the author tests and encodes and escapes these symbols, most json strings can be converted into json objects. If you encounter some problems, you should look for the problem in this direction.
TheString = theString. replace (">", ">"); theString = theString. replace ("<", "<"); theString = theString. replace ("", ""); theString = theString. replace ("\" "," "); theString = theString. replace ("\ '", "'"); theString = theString. replace ("\\", "\\\\"); // escape theString = theString for the diagonal line. replace ("\ n", "\ n"); theString = theString. replace ("\ r", \ r );
Note: \ r returns to the beginning of the line, and \ n is the new line. Both of them appear at the same time and should be processed at the same time.
Supplement: line breaks in the middle of the text. spaces are not displayed in the database in the form of \ r \ n; (line breaks between "book" and "first 80, space between "by" and "Cao Xueqin)
Text:
Database:
How can I convert a JSON string to a JS object?
Json format requirements are simple. Any amount that appears must be enclosed in double quotation marks '{"name": "zs", "age": "3"}'.
Second, evalJSON () does not know where the above method is. jQuery provides a method to parse string as json. jQuery. parseJSON (str)
Java converts a Json string to an object
Use Gson. : Code.google.com/p/google-gson/downloads/list
Define Java class:
Class Feature {public Attributes attributes; public Geometry geometry;} class Attributes {public String OBJECTID, ID, CD, HG, DP_AS .......;} class Geometry {public Float x, y;} Feature feature; public static MyObject fromJson (String json) {return new Gson (). fromJson (json, MuObject. class) ;}} and then call it as needed:
MyObject obj = MyObject. fromJson ("{......} "); MyObject. attributes attributes = obj. feature. attributes; MyObject. geometry geometry = obj. feature. geometry;