none
Most Current way to deserialize JSON feed

    General discussion

  • I see different ways of deserializing JSON feeds. Some of the posts are dated. Could I get a recommendation and some sample code for most current best practice to do this in C#.

    Thanks in Advance!

    Tuesday, April 11, 2017 12:59 PM

All replies

  • Hi DDL19,

    Please look into the below article/ JSON Documentation. You could use JsonConvert. Hope this helps you.

    Serializing and Deserializing JSON


    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]



    Tuesday, April 11, 2017 3:28 PM
    Moderator
  • Consider the DataContractJsonSerializer class too: https://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx. Add a reference to System.Runtime.Serialisation and try this example:

    [DataContract]
    class Person
    {
       [DataMember]
       public string name;
    
       [DataMember]
       public int age;
    }
    
    

    In Main function:

    Person p = new Person { name = "John", age = 150 };
    
    // serialisation:
    
    string json;
    
    using( MemoryStream stream = new MemoryStream() )
    {
       DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( Person ) );
       ser.WriteObject( stream, p );
       json = Encoding.UTF8.GetString( stream.ToArray() );
    }
    
    Console.WriteLine( json );
    
    // deserialisation:
    
    Person p2;
    
    using( MemoryStream stream = new MemoryStream( Encoding.UTF8.GetBytes( json ) ) )
    {
       DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( Person ) );
       p2 = (Person)ser.ReadObject( stream );
    }
    
    Console.WriteLine( p2.name );
    Console.WriteLine( p2.age );
    

    Tuesday, April 11, 2017 7:29 PM