Parse JSON String into List

后端 未结 5 2112
借酒劲吻你
借酒劲吻你 2021-02-14 11:55
string json = \"{\\\"People\\\":[{\\\"FirstName\\\":\\\"Hans\\\",\\\"LastName\\\":\\\"Olo\\\"}
                            {\\\"FirstName\\\":\\\"Jimmy\\\",\\\"LastName\         


        
相关标签:
5条回答
  • 2021-02-14 12:34

    Try this:

    using System;
    using Newtonsoft.Json;
    using System.Collections.Generic;
    public class Program
    {
        public static void Main()
        {
            List<Man> Men = new List<Man>();
    
            Man m1 = new Man();
            m1.Number = "+1-9169168158";
            m1.Message = "Hello Bob from 1";
            m1.UniqueCode = "0123";
            m1.State = 0;
    
            Man m2 = new Man();
            m2.Number = "+1-9296146182";
            m2.Message = "Hello Bob from 2";
            m2.UniqueCode = "0125";
            m2.State = 0;
    
            Men.AddRange(new Man[] { m1, m2 });
    
            string result = JsonConvert.SerializeObject(Men);
            Console.WriteLine(result);  
    
            List<Man> NewMen = JsonConvert.DeserializeObject<List<Man>>(result);
            foreach(Man m in NewMen) Console.WriteLine(m.Message);
        }
    }
    public class Man
    {
        public string Number{get;set;}
        public string Message {get;set;}
        public string UniqueCode {get;set;}
        public int State {get;set;}
    }
    
    0 讨论(0)
  • 2021-02-14 12:48

    Since you are using JSON.NET, personally I would go with serialization so that you can have Intellisense support for your object. You'll need a class that represents your JSON structure. You can build this by hand, or you can use something like json2csharp to generate it for you:

    e.g.

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    public class RootObject
    {
        public List<Person> People { get; set; }
    }
    

    Then, you can simply call JsonConvert's methods to deserialize the JSON into an object:

    RootObject instance = JsonConvert.Deserialize<RootObject>(json);
    

    Then you have Intellisense:

    var firstName = instance.People[0].FirstName;
    var lastName = instance.People[0].LastName;
    
    0 讨论(0)
  • 2021-02-14 12:48

    Wanted to post this as a comment as a side note to the accepted answer, but that got a bit unclear. So purely as a side note:

    If you have no need for the objects themselves and you want to have your project clear of further unused classes, you can parse with something like:

    var list = JObject.Parse(json)["People"].Select(el => new { FirstName = (string)el["FirstName"], LastName = (string)el["LastName"] }).ToList();
    
    var firstNames = list.Select(p => p.FirstName).ToList();
    var lastNames = list.Select(p => p.LastName).ToList();
    

    Even when using a strongly typed person class, you can still skip the root object by creating a list with JObject.Parse(json)["People"].ToObject<List<Person>>() Of course, if you do need to reuse the objects, it's better to create them from the start. Just wanted to point out the alternative ;)

    0 讨论(0)
  • 2021-02-14 12:52

    I use this JSON Helper class in my projects. I found it on the net a year ago but lost the source URL. So I am pasting it directly from my project:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Runtime.Serialization.Json;
    using System.IO;
    using System.Text;
    /// <summary>
    /// JSON Serialization and Deserialization Assistant Class
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// JSON Serialization
        /// </summary>
        public static string JsonSerializer<T> (T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }
        /// <summary>
        /// JSON Deserialization
        /// </summary>
        public static T JsonDeserialize<T> (string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }
    }
    

    You can use it like this: Create the classes as Craig W. suggested.

    And then deserialize like this

    RootObject root = JSONHelper.JsonDeserialize<RootObject>(json);
    
    0 讨论(0)
  • 2021-02-14 12:59

    Seems like a bad way to do it (creating two correlated lists) but I'm assuming you have your reasons.

    I'd parse the JSON string (which has a typo in your example, it's missing a comma between the two objects) into a strongly-typed object and then use a couple of LINQ queries to get the two lists.

    void Main()
    {
        string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"},{\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}";
    
        var result = JsonConvert.DeserializeObject<RootObject>(json);
    
        var firstNames = result.People.Select (p => p.FirstName).ToList();
        var lastNames = result.People.Select (p => p.LastName).ToList();
    }
    
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    public class RootObject
    {
        public List<Person> People { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题