C# Handle json There are two main ways to file :

(1) Use JavaScriptSerializer class , Need to introduce System.Web.Extension library , And add the following two references :

using System.Web;
using System.Web.Script.Serialization;

The main codes are as follows :

 public class Data
{
public int Id { get; set; }
// [ScriptIgnore]
public string Name { get; set; } public string GetName()
{
return Id.ToString() + Name;
}
} public class JsonPaserWeb
{
// Object->Json
public string Serialize(Data obj)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
string json = jsonSerializer.Serialize(obj);
return json;
} // Json->Object
public Data Deserialize(string json)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
// Perform deserialization
Data obj = jsonSerializer.Deserialize<Data>(json);
return obj;
}
}

have access to [ScriptIgnore] Tag so that a variable does not participate in serialization .

(2) Use DataContractJsonSerializer class , Need to introduce System.Runtime.Serialization library , And add the following reference :

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

The sample code is as follows :

 [DataContract]
public class Data
{
[DataMember(Name = "id", Order = )]
public int Id; [DataMember(Name = "name", Order = )]
public string Name; [DataMember(Name = "child", Order = )]
public Child child = new Child(); [DataMember(Name = "list", Order = )]
public List<int> Ids = new List<int>(); [DataMember(Name = "dictionary", Order = )]
public Dictionary<int, Child> dic = new Dictionary<int, Child>(); [IgnoreDataMember]
public string Description = "This is a json data class"; } public class Child
{
public float Age;
public string FullName;
} class JsonParserRuntime
{
// Object->Json
public string Serialize(Data obj)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
string json = "";
using (MemoryStream stream = new MemoryStream())
{
jsonSerializer.WriteObject(stream, obj);
json = Encoding.UTF8.GetString(stream.ToArray());
}
return json;
} // Json->Object
public Data Deserialize(string json)
{
Data obj = null;
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Data));
obj = (Data)jsonSerializer.ReadObject(ms);
}
return obj;
}
}

Use [DataContract] Marked class , Can be used at the same time [DataMember(Name = "id", Order = 0)] Tag to handle variables , You can also use [IgnoreDataMember] Tag so that a variable does not participate in serialization .

C# Reading and writing Json More articles about

  1. Android Reading and writing JSON One of the data formats JsonWriter and JsonReader

    I haven't done it in recent months Android Programming the , Gradually forget something . I'm looking for a job in the near future Android The job of , We should continue to pick up what we have . There has been no Internet since the company moved at the beginning of this month , It's not until today that companies have access to the Internet , The departments just started to work ...

  2. python Reading and writing json file (dump, load), And right json Format data processing (dumps, loads)

    JSON (JavaScript Object Notation) Is a lightweight data exchange format . It's based on ECMAScript A subset of . 1.json.dumps() and json.loads() yes json ...

  3. Reading and writing JSON Make configuration file

    I don't like it very much XML, So I found JSON To configure ,JSON Although there are a lot of quotes , But this key-value In the form of , Very much in line with my thinking , It's like a radish, a pit . I've been reading and writing recently JSON file , Two issues need to be noted . Chinese garbled : straight ...

  4. iOS How to use JSONKit Reading and writing JSON file

      How to use JSONKit Reading and writing JSON file classification : ios2013-04-20 12:46 510 Human reading   Comment on (0)  Collection   report JSON The file format is simple , Easy to use , It's worth it . Currently, there are several libraries supporting Json writing ...

  5. Qt Reading and writing Json

    Qt operation Json 1.QJsonDocument 1. Detailed instructions QJsonDocument Class provides read and write JSON Method of documentation . QJsonDocument It's a whole package JSON Class of document , Can be based on UTF ...

  6. python Reading and writing json file

    json The advantages of : 1. Data volume . JSON be relative to XML Speaking of , The volume of data is small , Faster delivery . 2. Transmission speed . JSON It's much faster than XML 3. data format The data format is relatively simple , Easy to read and write , ...

  7. java How to read and write json file

    In actual project development , Sometimes we encounter some global configuration cache , The best thing to do is to configure redis Database as data cache , And when there is no configuration redis Server time , Read static resource file ( Such as xml.json etc. ) It's also a way to achieve , But there's one drawback ...

  8. golang(7): File read and write &amp; json &amp; Error handling

    Terminal reading and writing Operator terminal related file handle constant os.Stdin // The standard input os.Stdout // standard output ( Output to terminal ) os.Stderr // Standard error output ( Output to terminal ) fmt Common use fm ...

  9. 【03】Python File read and write JSON

    1 Open file File operation steps : 1. Open the file and get the handle to the file , The handle is understood as this file 2. Manipulate files through file handles 3. Close file . 1.1 Open method f = open('xxx.txt') # Need to be f.close( ...

  10. C++ analysis Json, Use JsonCpp Reading and writing Json data

    JSON(JavaScript Object Notation, JS Object tag ) Is a lightweight data exchange format . Usually used for data exchange or storage . JsonCpp It's based on C++ Open source library for languages , be used for C++ programmatic J ...

Random recommendation

  1. 【WPF】 Borderless form

    Before writing a support size transformation of the borderless form of a base form , The code is as follows : public class LBaseWindow : Window { /// <summary> /// Base form /// & ...

  2. Use... On the server operating system TeamViewer

    TeamViewer Free license for personal or non-commercial use , It can be used permanently . But for corporate or commercial use only 7 Days probation period , It can't be used after the probation period . stay Windows XP And other non server operating systems TeamView ...

  3. [Windwos Phone] Implement map zoom MapAnimationKind Attribute effect

    original text :[Windwos Phone] Implement map zoom MapAnimationKind Attribute effect [ Preface ] Use latitude and longitude to position the map , And the use of MapAnimationKind Property to set the ...

  4. ng-option

    select  yes AngularJS A set of presuppositions directive. Here is its official website api doc The usage given :AngularJS:select The main idea is ,select Medium ngOption Can adopt and ngRep ...

  5. ubuntu 18 The graphical interface

    sh .start_mode.sh: Change the mode of operation ( The graphical interface , Terminal interface ): The desktop version : In the interface ctrl + shift + t Open the terminal ctrl + shift + "+" Enlarge character ...

  6. solve ScrollView nesting RecyclerView The display and sliding problem of

        Projects often need to be implemented in ScrollView To embed one or more RecyclerView. This practice usually leads to the following problems The page slides and gets stuck ScrollView The altitude display is abnormal RecyclerView Content ...

  7. ExtJS Tutorial directory

    Today I created a group , The name ExtJS Mutual aid groups , Welcome friends to join ! Don't forget when you have problems and need help ExtJS Mutual aid groups ! I hope more garden friends will join in , Help others , Also help yourself ! The group discussion is not limited to ExtJS, It also includes FineUI.Ex ...

  8. Linux Next Oracle Common commands

    1. Backup tables exp database_user/pass tables='(table1,table2)' file=filename.dmp( for example :exp ismrenbao/iflytek ta ...

  9. Cattle from java Basic knowledge of

    1.java Convert a large range number to a small range number , A cast is required . Java in , Data types are divided into basic data types ( Or called a primitive class . Built in type ) And reference data types . The native type is the basic data type int Can Boolean and Boolean be converted to each other ? ...

  10. oracle Insert

    Normal insertion : insert into t select * from t2; append Insert the way : insert /*+append*/ into t select * from t2; Appe ...