简体   繁体   English

如何使用C#将JSON转换为对象

[英]How to convert JSON to object with C#

I am having trouble accessing the properties in my json file. 我无法访问json文件中的属性。 I need to create ac# object with it too. 我也需要使用它创建ac#对象。 It is not able to work properly. 它无法正常工作。 This requires the need to drill down several classes, where I cannot find any other documentation on it, as most use a very simple json file. 这需要深入研究几个类,在其中我找不到其他任何文档,因为大多数使用的是非常简单的json文件。

{
    "type": "FeatureCollection",
    "features": [
        { 
            "type": "Feature",
            "properties": 
            { 
                "TYPE": "COASTAL", 
                "R_STATEFP": "28", 
                "L_STATEFP": "" 
            }, 
            "geometry": 
            { 
                "type": "LineString", 
                "coordinates": [ 
                    [ -88.453654, 30.196584 ], 
                    [ -88.428301, 30.198511 ], 
                    [ -88.404581, 30.206162 ], 
                    [ -88.401466, 30.210172 ], 
                    [ -88.430332, 30.208548 ], 
                    [ -88.442654, 30.202314 ], 
                    [ -88.453444, 30.201236 ], 
                    [ -88.465713, 30.202540 ], 
                    [ -88.500011, 30.214044 ], 
                    [ -88.506999, 30.214348 ], 
                    [ -88.502752, 30.210506 ], 
                    [ -88.493523, 30.205945 ], 
                    [ -88.453654, 30.196584 ] 
                ]  
            } 
        },
        //repeated 100+ times
    ]
}   

This is my classes file: 这是我的班级文件:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MyApp
{
    public class FeatureCollection
    {
        public string type{ get; set; }
        public List<Feature> features{ get; set; }
        [JsonConstructor]

        public FeatureCollection(JObject i)
        {
            var typeProp = i.GetType().GetProperty("type");
            this.type = typeProp.GetValue(i) as string;
            JArray features = (JArray)i.GetValue("features");
            this.features = new List<Feature>();
            foreach (JObject f in features)
            {
                this.features.Add(new Feature(f));
                Console.Write(features);
            }
        }
    }

    public class Feature
    {
        public string type;
        public Property properties;
        public Geometry geometry;

        [JsonConstructor]
        public Feature(JObject i)
        {
            var typeProp = i.GetType().GetProperty("type");
            this.type = typeProp.GetValue(i) as string;
            var prop = i.GetValue("properties") as JObject;
            this.properties = new Property(prop);
            var geo = i.GetValue("geometry") as JObject;
            this.geometry = new Geometry(geo);
        }

    }

    public class Property
    {
        public string TYPE;
        public string R_STATEFP;
        public string L_STATEFP;

        [JsonConstructor]
        public Property(JObject i)
        {
            var typeProp = i.GetType().GetProperty("TYPE");
            this.TYPE = typeProp.GetValue(i) as string;
            var typeR = i.GetType().GetProperty("type");
            this.R_STATEFP = typeR.GetValue(i) as string;
            var typeL = i.GetType().GetProperty("type");
            this.L_STATEFP = typeL.GetValue(i) as string;
        }
    }

    public class Geometry
    {
        public string type;
        public List<Coord> coordinates;

        [JsonConstructor]
        public Geometry(JObject i)
        {
            var typeProp = i.GetType().GetProperty("type");
            this.type = typeProp.GetValue(i) as string;
            JArray coordinates = (Newtonsoft.Json.Linq.JArray)i.GetValue("coordinates");
            this.coordinates = new List<Coord>();
            foreach (JArray c in coordinates)
            {
                this.coordinates.Add(new Coord(c));
            }
        }
    }

    public class Coord
    {
        public double longitude;
        public double latitude;

        [JsonConstructor]
        public Coord(JArray a){
            this.longitude = (double)a[0];
            this.latitude = (double)a[1];
        }
    }
}

Also, what is the best way to open such a large file in the main (assume it will be 100+ features) will streamreader be the best route? 另外,在主目录中打开这么大文件的最佳方法是什么(假设它将有100多个功能),streamreader将是最佳途径吗?

Thank you 谢谢

You can simplify your design quite a bit. 您可以相当简化您的设计。

If you make your classes just plain ol' classes that represent your data: 如果使您的类只是代表数据的普通类,则:

public class Properties
{
    public string Type { get; set; }

    [JsonProperty(PropertyName = "R_STATEFP")]
    public string RState { get; set; }

    [JsonProperty(PropertyName = "L_STATEFP")]
    public string LState { get; set; }
}

public class Geometry
{
    public string Type { get; set; }    
    public List<List<double>> Coordinates { get; set; }
}

public class Feature
{
    public string Type { get; set; }
    public Properties Properties { get; set; }
    public Geometry Geometry { get; set; }
}

public class RootObject
{
    public string Type { get; set; }
    public List<Feature> Features { get; set; }
}

You can then use JsonConvert.DeserializeObject<T>() to deserialize (and in the inverse JsonConvert.Serialize() to serialize). 然后,您可以使用JsonConvert.DeserializeObject<T>()进行反序列化(并在反JsonConvert.Serialize()进行序列化)。

RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(jsonString);

You can see it in action here 您可以在这里看到它的运行情况

如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C#

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将C#对象转换为JSON对象 - How to convert c# object to json object 如何在C#中将json字符串转换为对象 - how to convert json string to object in C# 如何将此json转换为C#对象 - How to convert this json into C# object 如何在C#中将Json对象转换为数组 - How to Convert Json Object to Array in C# 如何将这个JSON到C#对象转换 - How to convert this JSON to C# object 如何转换列表<object>至 Json | C#<div id="text_translate"><p> 我有一个由对象组成的列表,每个 object 有 5 个数据。 我需要将该列表转换为 json,但使用序列化它会填满空的 json。</p><p> 有谁知道我可能做错了什么?</p><pre> foreach (DataRow dtRow in dtAlarmas.Rows) { String Name = dtRow["Name"].ToString(); String ID = dtRow["ID"].ToString(); String AlarmText = dtRow["AlarmText"].ToString(); String AlarmTimeNoNula = dtRow["AlarmTimeNoNula"].ToString(); lstAlarmasNoTratadas.Add(new Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel(dtRow["Name"].ToString(), Convert.ToInt32(dtRow["ID"]), dtRow["Class"].ToString(), dtRow["AlarmText"].ToString(), dtRow["AlarmTimeNoNula"].ToString())); } string sParams = JsonConvert.SerializeObject(lstAlarmasNoTratadas);</pre><p> 转换后的 sParams 值 = "[{}]"</p><p> Class Ondoan.DatosAux.Alarmas.AlarmaNoTratadaModel</p><pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ondoan.DatosAux.Alarmas { public class AlarmaNoTratadaModel { private string Name; private int ID; private string Class; private string AlarmText; private string AlarmaTimeNoNula; public AlarmaNoTratadaModel(string Name, int ID, string Class, string AlarmText, string AlarmaTimeNoNula) { // TODO: Complete member initialization this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula; } public class AlarmaNoTratadasModel { public AlarmaNoTratadasModel() { } public AlarmaNoTratadasModel(String Name, Nullable&lt;System.Int32&gt; ID, String Class, String AlarmText, String AlarmaTimeNoNula) { this.Name = Name; this.ID = ID; this.Class = Class; this.AlarmText = AlarmText; this.AlarmaTimeNoNula = AlarmaTimeNoNula.ToString(); } public System.String Name { get; set; } public Nullable&lt;System.Int32&gt; ID { get; set; } public System.String Class { get; set; } public System.String AlarmText { get; set; } public System.String AlarmaTimeNoNula { get; set; } } } }</pre></div></object> - How to Convert List<Object> to Json | C# 如何在C#中将json数据转换为对象? - How to convert json data to object in C#? 如何将 Json 转换为 C# object? - How to convert Json into C# object? 如何在C#中将json对象转换为字符串? - How to convert json object to string in C#? 如何将动态 JSON 转换为 C# object - How to convert dynamic JSON to C# object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM