Json.net allows convenient transfer Json C # (dynamic dynamic type) object

The period required before conversion to C # json string objects, usually a class definition entities corresponding to the reception. This has a big drawback is that when a string particularly long, particularly property, there are nested, hand to knock the entity class is very painful.

For example, before doing a weather forecast seven days of receiving the Baidu API, nested layers, very painful.

With dynamic type dynamic following C # 4.0. With this thing with Json.net can be achieved without defining entity classes json turn dynamic type of the object.

The following example will need to reference Newtonsoft.Json.dll

public class Person {
    public int Id { get; set; }
    public string Name { get; set; }
} 
class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();
        p.Id = 1;
        p.Name = "刘备";
        //C#对象转Json
        string json =JsonConvert.SerializeObject (P); 
        Console.WriteLine (json);     // { "Id":. 1, "the Name": "Bei"} 
         
        // case here not build simulation entity class, the reverse return json dynamic objects 
        var DynamicObject = JsonConvert.DeserializeObject < dynamic > (JSON); 
        Console.WriteLine (DynamicObject.Name);   // Bei 
        the Console.ReadKey (); 
    } 
}

These are just borrowed an entity class to get a simple JSON object.

In fact, this may be no Person class.

static  void the Main ( String [] args) 
{ 
    String JSON = " {\" Id \ ":. 1, \" the Name \ ": \" Bei \ ", \" Age \ ": \" 22 is \ "} " ;
     / / case here not build simulation entity class, the inverted dynamic objects json returns back 
    var DynamicObject = JsonConvert.DeserializeObject < dynamic > (json); 
    Console.WriteLine (DynamicObject.Name);   // Bei 
    the Console.ReadKey ( ); 
}

If no reference Microsoft.CSharp.dll, on the dynamic type, VS can cause an error.

VS can return compile error: Can not find the required compile one or more types of dynamic expressions. Are you missing a reference?

Guess you like

Origin www.cnblogs.com/leebokeyuan/p/11310606.html