Parsing JSON using Json.net

后端 未结 5 1025
既然无缘
既然无缘 2020-11-22 07:19

I\'m trying to parse some JSON using the JSon.Net library. The documentation seems a little sparse and I\'m confused as to how to accomplish what I need. Here is the forma

5条回答
  •  生来不讨喜
    2020-11-22 08:11

    I don't know about JSON.NET, but it works fine with JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1):

    using System.Collections.Generic;
    using System.Web.Script.Serialization;
    public class NameTypePair
    {
        public string OBJECT_NAME { get; set; }
        public string OBJECT_TYPE { get; set; }
    }
    public enum PositionType { none, point }
    public class Ref
    {
        public int id { get; set; }
    }
    public class SubObject
    {
        public NameTypePair attributes { get; set; }
        public Position position { get; set; }
    }
    public class Position
    {
        public int x { get; set; }
        public int y { get; set; }
    }
    public class Foo
    {
        public Foo() { objects = new List(); }
        public string displayFieldName { get; set; }
        public NameTypePair fieldAliases { get; set; }
        public PositionType positionType { get; set; }
        public Ref reference { get; set; }
        public List objects { get; set; }
    }
    static class Program
    {
    
        const string json = @"{
      ""displayFieldName"" : ""OBJECT_NAME"", 
      ""fieldAliases"" : {
        ""OBJECT_NAME"" : ""OBJECT_NAME"", 
        ""OBJECT_TYPE"" : ""OBJECT_TYPE""
      }, 
      ""positionType"" : ""point"", 
      ""reference"" : {
        ""id"" : 1111
      }, 
      ""objects"" : [
        {
          ""attributes"" : {
            ""OBJECT_NAME"" : ""test name"", 
            ""OBJECT_TYPE"" : ""test type""
          }, 
          ""position"" : 
          {
            ""x"" : 5, 
            ""y"" : 7
          }
        }
      ]
    }";
    
    
        static void Main()
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();
            Foo foo = ser.Deserialize(json);
        }
    
    
    }
    

    Edit:

    Json.NET works using the same JSON and classes.

    Foo foo = JsonConvert.DeserializeObject(json);
    

    Link: Serializing and Deserializing JSON with Json.NET

提交回复
热议问题