Parsing JSON object containing an array with Windows Phone 7

前端 未结 3 1219
终归单人心
终归单人心 2021-01-14 17:36

Ok, I\'m having some difficult with this.

My JSON is like

{ \"names\" : [ {\"name\":\"bla\"} , {\"name\":\"bla2\"} ] }

I was trying

相关标签:
3条回答
  • 2021-01-14 18:00

    I'm using JSON.NET ( http://james.newtonking.com/projects/json-net.aspx ) normally, so my code might vary a bit.

    For the list content I would go for a class with a name property like that:

    public class NameClass {
        public string name { get;set; }
    }
    

    Then you should be able to deserialize with JSON.NET a List<NameClass>:

    List<NameClass> result = JsonConvert.Deserialize<List<NameClass>>(jsonString);
    

    This is written out of my head, so maybe, it doesn't compile with copy and paste, but it should work as a sample.

    0 讨论(0)
  • 2021-01-14 18:07

    Using Json.Net (which supports Windows Phone)

    string json = @"{ ""names"" : [ {""name"":""bla""} , {""name"":""bla2""} ] }";
    
    var dict = (JObject)JsonConvert.DeserializeObject(json);
    foreach (var obj in dict["names"])
    {
        Console.WriteLine(obj["name"]);
    }
    

    Or if you want to use it in a type-safe way

    var dict = JsonConvert.DeserializeObject<RootClass>(json);
    foreach (var obj in dict.names)
    {
        Console.WriteLine(obj.name);
    }
    
    
    public class RootClass
    {
        public MyName[] names { get; set; }
    }
    
    public class MyName
    {
        public string name { get; set; }
    }
    
    0 讨论(0)
  • 2021-01-14 18:12

    Using the .NET DataContractJsonSerializer you will need to define a class that maps the json objects. Something like this (if i remember correctly):

    /// <summary>
    /// 
    /// </summary>
    [DataContract]
    public class Result
    {
        /// <summary>
        /// 
        /// </summary>
        [DataMember(Name = "name")]
        public string Name
        { get; set; }
    }
    
     /// <summary>
    /// 
    /// </summary>
    [DataContract]
    public class Results
    {
        /// <summary>
        /// 
        /// </summary>
        [DataMember(Name = "names")]
        public List<Result> Names
        { get; set; }
    }
    

    then in your event handler:

    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Results));
    var results = (Results)serializer.ReadObject(SOME OBJECT HOLDING JSON, USUALLY A STREAM);
    
    0 讨论(0)
提交回复
热议问题