Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write JSON string value in code?

I want to store the following string in a String variable

{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}

This is the code I use ..

String str="{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}"; 

.. but it's showing error ..

like image 373
user1811801 Avatar asked Nov 21 '12 08:11

user1811801


People also ask

How do I convert a JSON to a string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

Is JSON string value?

No, JSON is not a string. It's a data structure.

What is JSON string format?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

What does a JSON string look like?

A JSON string contains either an array of values, or an object (an associative array of name/value pairs). An array is surrounded by square brackets, [ and ] , and contains a comma-separated list of values. An object is surrounded by curly brackets, { and } , and contains a comma-separated list of name/value pairs.


2 Answers

You have to do this

String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}"; 


Please see this for reference
Also from msdn :)

Short Notation  UTF-16 character    Description \'  \u0027  allow to enter a ' in a character literal, e.g. '\'' \"  \u0022  allow to enter a " in a string literal, e.g. "this is the double quote (\") character" \\  \u005c  allow to enter a \ character in a character or string literal, e.g. '\\' or "this is the backslash (\\) character" \0  \u0000  allow to enter the character with code 0 \a  \u0007  alarm (usually the HW beep) \b  \u0008  back-space \f  \u000c  form-feed (next page) \n  \u000a  line-feed (next line) \r  \u000d  carriage-return (move to the beginning of the line) \t  \u0009  (horizontal-) tab \v  \u000b  vertical-tab 
like image 166
Freak Avatar answered Sep 23 '22 17:09

Freak


I prefer this, just make sure you don't have single quote in the string

 string str = "{'Id':'123','DateOfRegistration':'2012-10-21T00:00:00+05:30','Status':0}"               .Replace("'", "\""); 
like image 25
Mohammad Nikravan Avatar answered Sep 22 '22 17:09

Mohammad Nikravan