How to get some values from a JSON string in C#?

前端 未结 4 2084
野的像风
野的像风 2020-11-29 22:14

I have a string and I want to get some values from it.

My strings seem like:

string1:

\"{\\r\\n   \\\"id\\\": \\\"100000280905615\\\",
 \\r\\         


        
4条回答
  •  孤独总比滥情好
    2020-11-29 22:46

    Create a class like this:

    public class Data
    {
        public string Id {get; set;}
        public string Name {get; set;}
        public string First_Name {get; set;}
        public string Last_Name {get; set;}
        public string Username {get; set;}
        public string Gender {get; set;}
        public string Locale {get; set;}
    }
    

    (I'm not 100% sure, but if that doesn't work you'll need use [DataContract] and [DataMember] for DataContractJsonSerializer.)

    Then create JSonSerializer:

    private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));
    

    and deserialize object:

    // convert string to stream
    byte[] byteArray = Encoding.UTF8.GetBytes(contents);
    using(var stream = new MemoryStream(byteArray))
    {
        (Data)Serializer.ReadObject(stream);
    }
    

提交回复
热议问题