Questions about JSON serialization and deserialization, nothing to write a case, hope to help those who need help friends!

Source: Internet
Author: User
Tags string to json

Now there are a lot of solutions to the problem of JSON reading and writing, depending on the actual problem to choose the easiest way to do. I think the Newtonsoft.json is a good choice, just write two examples!

One: For simple Json serialization and deserialization, you can use the Newtonsoft.json+ entity class to solve.
Let's start with a Jsonhelp class.

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Runtime.Serialization.Json;
Using System.IO;
Using System.Text;
Using System.Text.RegularExpressions;
Namespace Serializationanddeserialization.code
{
public class Jsonhelp
{
<summary>
JSON serialization
</summary>
public static string jsonserializer<t> (T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T));
MemoryStream ms = new MemoryStream ();
Ser. WriteObject (MS, T);
String jsonstring = Encoding.UTF8.GetString (ms. ToArray ());
Ms. Close ();
Replace the JSON date string
String p = @ "\\/date\ ((\d+) \+\d+\) \\/";
MatchEvaluator matchevaluator = new MatchEvaluator (convertjsondatetodatestring);
Regex reg = new regex (p);
jsonstring = Reg. Replace (jsonstring, MatchEvaluator);
return jsonstring;
}

<summary>
JSON deserialization
</summary>
public static T jsondeserialize<t> (String jsonstring)
{
Convert a string "Yyyy-mm-dd HH:mm:ss" to "\/date (1294499956278+0800)/" format
String p = @ "\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchevaluator = new MatchEvaluator (convertdatestringtojsondate);
Regex reg = new regex (p);
jsonstring = Reg. Replace (jsonstring, MatchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T));
MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (jsonstring));
T obj = (t) ser. ReadObject (MS);
return obj;
}

<summary>
Convert JSON serialized time from/date (1294499956278+0800) to string
</summary>
private static string convertjsondatetodatestring (Match m)
{
string result = String. Empty;
DateTime dt = new DateTime (1970,1,1);
DT = dt. Addmilliseconds (Long. Parse (M.groups[1]. Value));
DT = dt. ToLocalTime ();
result = dt. ToString ("Yyyy-mm-dd HH:mm:ss");
return result;
}

<summary>
Convert time string to JSON time
</summary>
private static string Convertdatestringtojsondate (Match m)
{
string result = String. Empty;
DateTime dt = DateTime.Parse (M.groups[0]. Value);
DT = dt. ToUniversalTime ();
TimeSpan ts = dt-datetime.parse ("1970-01-01");
result = String. Format ("\\/date ({0}+0800) \\/", TS. TotalMilliseconds);
return result;
}
}
}

Step two: Build two entity classes to use:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Namespace Serializationanddeserialization.code
{
public class Model1
{
public string code {get; set;}
public string Description {get; set;}
}
}

public class Model2
{
public string name {get; set;}
public string Age {get; set;}
public string Sex {get; set;}
Public love love {get; set;}


}
public class Love
{

public string Play {get; set;}
public string Music {get; set;}
}

And then there's a test case:

1: Serialization of JSON:

private void Test2 ()
{

list<model2> list = new list<model2> ();


Love L = new Love ();
L.music = "Music";
L.play = "basketball";
Model2 m = new Model2 ();
M.name = "Xiao Ming";
M.age = "18";
M.sex = "male";
M.love = l;

List. ADD (m);


Love lo = new Love ();
Lo. Music = "singing";
Lo. Play = "Dance";
Model2 m1 = new Model2 ();
M1.name = "Xiao Wang";
M1.age = "19";
M1.sex = "male";
M1.love = lo;
List. ADD (M1);

string result = Jsonhelp.jsonserializer<list<model2>> (List);
Response.Write (Result);

}

2: First serialize and then deserialize the effect:

private void Test1 ()
{
Model1 m = new Model1 ();
M.code = "00000";
M.description = "succeeded";
string result = Jsonhelp.jsonserializer<model1> (M);


Model1 mm = jsonhelp.jsondeserialize<model1> (result);
Response.Write (mm.description + "..." + mm.code);
Response.Write (Result);
}

But.... For a complex JSON, would you like to write the entity classes in JSON view? Again build entity class personally feel very troublesome, not is different JSON format will write an entity class, not very good choice ...

Here's a combination of the Newtonsoft.json and the dynamic type to parse the JSON:

The JSON format is:

{
"Svccont": [
{
"Pub_req": {
"TYPE": "Add_test_bean"
},
"Result": {
"ResultCode": "0",
"Resultdata": {
"AccountNumber": "05519430313",
"Areaid": "0001",
"ServiceType": 201,
"Vbrestvalue": 0,
"Vbtotalvalue": 0
},
"Resultmsg": "Success"
}
}
],
"Tcpcont": {
"LATNCD": "551",
"Servicecode": "FUNC99002",
"Srcorgid": "30",
"Srcsysid": "1030",
"Srcsyssign": "5273c8fd1c9b483a1a8bc49baf363987",
"TransactionID": "20140709101229"
}
}

Now I'll say how to get: ResultCode and RESULTMSG values!

Simulating JSON strings

string ss = "{\" svccont\ ": [{\" pub_req\ ": {\" type\ ": \" add_test_bean\ "},\" result\ ": {\" resultcode\ ": \" 0\ ", \" Resultdata\ ": {\" accountnumber\ ": \" 05519430313\ ", \" areaid\ ": \" 0001\ ", \" servicetype\ ": 201,\" vbrestvalue\ ": 0,\" Vbtotalvalue\ ": 0},\" resultmsg\ ": \" success \ "}}],\" tcpcont\ ": {\" latncd\ ": \" 551\ ", \" servicecode\ ": \" func99002\ ", \" Srcorgid\ ": \" 30\ ", \" srcsysid\ ": \" 1030\ ", \" srcsyssign\ ": \" 5273c8fd1c9b483a1a8bc49baf363987\ ", \" Transactionid\ " : \ "20140709101229\"}} ";

Step-by-step parsing, according to your own requirements and the JSON format of a layer of deserialization

if (ss. StartsWith ("{") && SS. EndsWith ("}")
|| Ss. StartsWith ("[") && SS. EndsWith ("]"))
{
Dynamic XX = newtonsoft.json.jsonconvert.deserializeobject<dynamic> (ss);
Dynamic Resultdata = newtonsoft.json.jsonconvert.deserializeobject<dynamic> (xx. Svccont.tostring ());
List<dynamic> pags = newtonsoft.json.jsonconvert.deserializeobject<list<dynamic>> ( Resultdata.tostring ());
foreach (var pag in pags)
{
Dynamic PAGSS = newtonsoft.json.jsonconvert.deserializeobject<dynamic> (pag.result.ToString ());
String code = pagss.resultCode.ToString ();
String msg = Pagss.resultMsg.ToString ();
Response.Write ("Code value is code:" + code + ", the value of mess is:" + msg);
}
}

OK, here is the simple JSON serialization and deserialization problem, I hope to help you!

Questions about JSON serialization and deserialization, nothing to write a case, hope to help those who need help friends!

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.