JSON Operations Library Dynamicjson use guide _c# tutorial

Source: Internet
Author: User
Tags foreach anonymous arrays php server serialization

Introduction to JSON

JSON (JavaScript Object notation) is a lightweight data interchange format. It is based on a subset of ECMAScript. JSON uses a completely language-independent text format, but it also uses a family of C-language (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 parsing and generation (generally used to improve network transmission rate).

The benefits of JSON

    1. Data format is simple, easy to read and write, the format is compressed, the use of small bandwidth
    2. Easy to parse, client JavaScript can simply read JSON data via eval ();
    3. Support for multiple languages, including ActionScript, C, C #, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and other server-side languages, easy server-side resolution;
    4. In the world of PHP, there have been Php-json and json-php appeared, biased in PHP after the serialization of the program directly call, PHP server-side objects, arrays, etc. can directly generate JSON format, easy access to the client to extract;
    5. Because the JSON format can be used directly for server-side code, it greatly simplifies the amount of code development on both the server and the client, and completes the task without change and is easy to maintain.

Legacy Operations JSON

A lot. NET developers are more or less in the process of manipulating JSON strings, in general, we first define a class that matches the JSON format and then deserialize the JSON string into objects so that we can programmatically use them because. NET is a strongly typed language, and JSON is variable and flexible, resulting in more and more JSON serialization classes that are defined on the server side, as well as their inconvenience. This is especially a headache for multiple layers of nested JSON. This time no longer too much declaration,. NET programmers used to understand.

Easy to manipulate JSON

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

How to use Dynamicjson in a project

Install directly through NuGet

PM > Install-Package DynamicJson

Download DynamicJson.dll, and then add a reference to the project, download the following address:

http://dynamicjson.codeplex.com/

Read, get

Parse JSON string into Dynamicjson object
var json = Dynamicjson.parse (@ "{" "foo" ":" "json", "Bar" ":," "nest" ": {" "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 it through the indexer like JavaScript.

Judge, add, update, delete, replace, and output new JSON strings

Parse JSON string into Dynamicjson object var json = Dynamicjson.parse (@ "{" "foo" ":" "json", "Bar" ":", "" nest "": {"" Foobar "": TR
 
      UE}} "); 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 be simpler, directly through JSON. The key () can be used to determine var b1_2 = Json.foo (); true var b2_2 = Json.foooo ();
 
 
      False New action JSON. ARR = new string[] {"NOR", "XOR"}; Add a JS array json. Obj1 = new {}; Add a JS object json. Obj2 = new {foo = ' abc ', bar = 100}; Initializes an anonymous object and adds it to the JSON string//deletes the operation JSON.
      Delete ("foo"); Json.
      Arr.delete (0); can also be simpler to delete, directly through the JSON (key);
      can be deleted.
      JSON ("Bar"); Json.
 
      ARR (1); Replace the operation JSON.
 
      OBJ1 = 5000;
      To create a new jsonobject dynamic Newjson = ();
      NEWJSON.STR = "AAA";
 
      Newjson.obj = new {foo = ' bar '}; Direct serialization 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///
 
      Direct traversal of 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 a JSON array to a C # array method one: var array1 = arrayjson.deserialize<int[]> ();
      Method two var array2 = (int[]) Arrayjson;
 
      Method Three, this simplest, direct declaration receive, 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 simplest, direct declaration receive can, recommend the use of FooBar foobar3 = Objectjson;
      You can also manipulate var objectjsonlist = Dynamicjson.parse (@ "[{" "Bar"]: 50},{"Bar" ": 100}]" by LINQ; var barsum = ((foobar[]) objectjsonlist). Select (FB => fb.bar). Sum (); The var dynamicwithlinq = ((dynamic[]) objectjsonlist). 
Select (d => d.bar); 

Serialized as a 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 ': ']
      var foobar = new foobar[] {
        New FooBar {foo = "fooooo!", bar = 1000},
        new FooBar {foo = "Orz", bar = ten}
      ;
      Serialization of
      var Jsonfoobar = dynamicjson.serialize (Foobar);

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

var Nestjson = Dynamicjson.parse (@ "{" "tes" ": Ten," "Nest" ": {" "a" ": 0}");
 
      Nestjson.nest (); To determine whether there is a Nest property
      nestjson.nest ("a");//delete The A attribute in the Nest property
 
      //Handle the key in JSON and C # type conflicts cause the compilation to fail, or syntax prompts are wrong, just precede the @ prefix
      var json = Dynamicjson.parse (@ "{" "int" ":" "" Event "": null} ");
      var r1 = json. @int; 10.0
      var r2 = json. @event;//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 cool, quickly let your project integration Dynamicjson bar.

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.