Allow C # to manipulate JSON like JavaScript

Source: Internet
Author: User
Tags php server

Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, and so on). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and generate (typically used to improve network transfer rates).

From the introduction of Baidu Encyclopedia

The advantages of JSON

    • Data format is simple, easy to read and write, the format is compressed, the use of small bandwidth
    • Easy to parse, client-side JavaScript can simply read the JSON data through Eval ();
    • Support multiple languages, including ActionScript, C, C #, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and other server-side languages, facilitate server-side parsing;
    • In the PHP world, there are already Php-json and json-php appear, partial to the PHP serialization program directly call, PHP server-side objects, arrays, etc. can directly generate JSON format, convenient for client access extraction;
    • Because the JSON format can be used directly for server-side code, it greatly simplifies the development of the server-side and the client's code, and completes the task unchanged, and is easy to maintain.

Traditional Operation JSON

A lot. NET development programmers are more or less in the case of manipulating JSON strings, in general, we define a class that matches the JSON format, and then deserialize the JSON string into an object so that we can use it programmatically, because. NET is a strong type language, JSON is also changeable, very flexible, resulting in the server-side definition of JSON serialization class more and more, operation and its inconvenience. Especially for multi-layered nested JSON is a headache. This time no longer declares too much,. NET programmers are used to understand.

Easy-to-operate JSON

Dynamicjson is a JSON operation library developed specifically for. NET programmers, whose source code is very simple, with only 400 lines, and a corresponding class class that currently only supports. NET 4.0. NET Framework.

How to use Dynamicjson in a project
    • Install directly from NuGet
PM > Install-package Dynamicjson
    • Download DynamicJson.dll, and then add a reference to the project as follows:
http://dynamicjson.codeplex.com/

Read, get

Parse the JSON string into the Dynamicjson object var json = Dynamicjson.parse (@ "{" "" foo "": "" "" "" "" "" "" "" "" "" "" ":" "" "", "" ": {" "Foobar" ": true} } "); var r1 = Json.foo; "JSON"-string type var r2 = Json.bar; 100-double type var r3 = Json.nest.foobar; True-bool type var r4 = json["nest" ["Foobar"]; You can also get through the indexer like JavaScript

  

Judging, adding, updating, deleting, replacing, and also outputting a new JSON string

Parse the JSON string into the Dynamicjson object var json = Dynamicjson.parse (@ "{" "" foo "": "" "" "" "" "" "" "" "" "" "": "" "" "" "" "" "": {"" Foobar "            ": True}}"); Determines whether the JSON string contains the specified key var b1_1 = json. IsDefined ("foo"); true var b2_1 = json. IsDefined ("foooo"); False//The above judgment can also be simpler, directly through the JSON. Key () can be judged var b1_2 = Json.foo (); true var b2_2 = Json.foooo ();            False Added action JSON. ARR = new string[] {"NOR", "XOR"}; Added a JS array json. Obj1 = new {}; Added a JS object json. Obj2 = new {foo = "abc", bar = 100}; Initializes an anonymous object and adds it to the JSON string//delete operation JSON.            Delete ("foo"); Json.            Arr.delete (0); can also be more simple to delete, directly through the JSON (key);            can be deleted.            JSON ("Bar"); Json.            ARR (1); Replace the operation JSON.            OBJ1 = 5000;            Create a new jsonobject dynamic Newjson = new Dynamicjson ();            NEWJSON.STR = "AAA";       Newjson.obj = new {foo = "bar"};     Direct serialization of the output JSON string var jsonstring = Newjson. ToString (); {"str": "AAA", "obj": {"foo": "Bar"}}

  

Traverse

Direct traversal of the JSON array            var Arrayjson = dynamicjson.parse (@ "[1,10,200,300]");            foreach (int item in Arrayjson)            {                Console.WriteLine (item);//1, ten, Max, +            }            //Direct traversal of the JSON object            var obj Ectjson = Dynamicjson.parse (@ "{" "foo" ":" "JSON" "," "Bar" ": +}");            foreach (keyvaluepair<string, dynamic> item in Objectjson)            {                Console.WriteLine (item. Key + ":" + Item. Value); Foo:json, bar:100            }

  

Conversion and deserialization

public class FooBar {public string foo {get; set;}        public int bar {get; set;}            }var Arrayjson = Dynamicjson.parse (@ "[1,10,200,300]");            var Objectjson = Dynamicjson.parse (@ "{" "foo" ":" "JSON" "," "Bar" ": 100}");            Convert JSON arrays to C # Arrays//Method One: var array1 = arrayjson.deserialize<int[]> ();            Method two var array2 = (int[]) Arrayjson;            Method Three, this is the simplest, direct declaration of receiving can be, recommend the use of int[] array3 = Arrayjson;            Map JSON strings to C # Objects//Method one: var foobar1 = objectjson.deserialize<foobar> ();            Method Two: var foobar2 = (FooBar) Objectjson;            Method Three, this is the simplest, direct declaration receive can, recommend using FooBar foobar3 = Objectjson;            You can also operate with LINQ by using var objectjsonlist = Dynamicjson.parse (@ "[{" "Bar" ": 50},{" "Bar" ": 100}]"); var barsum = ((foobar[]) objectjsonlist). Select (fb = Fb.bar). Sum (); The var dynamicwithlinq = ((dynamic[]) (objectjsonlist). Select (d = d.bar);

  

Serialize into JSON string

Declares an anonymous object            var obj = new            {                Name = "Foo", age                = +,                Address = new                {                    country = "Japan",                    Cit y = "Tokyo"                }, like                = new[] {"Microsoft", "Xbox"}            };            Serialization            //{"Name": "Foo", "age": +, "Address": {"Country": "Japan", "City": "Tokyo"}, "like": ["Microsoft", "Xbox"]}            var jsonstringfromobj = dynamicjson.serialize (obj);            also supports direct serialization of arrays, collections            //[{"foo": "Fooooo!", "Bar": 1000},{"foo": "Orz", "Bar": ten}]            var foobar = new foobar[] {                New FooBar {foo = "fooooo!", bar = $},                new FooBar {foo = "Orz", bar = ten}            ;            Serialization of            var Jsonfoobar = dynamicjson.serialize (Foobar);

  

Other (conflict issues, compilation does not pass the issue)

var Nestjson = Dynamicjson.parse (@ "{" "tes" ": Ten," "Nest" ": {" "a" ": 0}");            Nestjson.nest (); Determine if the nest attribute is present            nestjson.nest ("a");//delete The A attribute in the Nest property            //Handle the JSON key and C # type conflict causes compilation to fail, or syntax hint error, only need to precede the @ prefix            var json = Dynamicjson.parse (@ "{" "int" ": Ten," "Event" ": null}");            var r1 = [email protected]; 10.0            var r2 = [email protected];//null

  

Example one: Twitterapi

static void Main () {    var publictl = new WebClient (). Downloadstring (@ "Http://twitter.com/statuses/public_timeline.json");    var statuses = Dynamicjson.parse (publictl);    foreach (var status in statuses)    {        Console.WriteLine (status.user.screen_name);        Console.WriteLine (Status.text);    }}

  

Example two: TwitterAPI2

static void Main (string[] args) {    var WC = new WebClient ();    var statuses = Enumerable.range (1, 5)        . Select (i =            WC. Downloadstring ("http://twitter.com/statuses/user_timeline/neuecc.json?page=" + i))        . SelectMany (s = = (dynamic[]) Dynamicjson.parse (s))        . (j = j.id);    foreach (var status in statuses)    {        Console.WriteLine (status.text);    }}

  

See here, is not feel very good, quickly let your project integration Dynamicjson bar.

Allow C # to manipulate JSON like JavaScript

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.