根据Json字符串创建C#的Model类

根据Json字符串创建C#的Model类

在C#项目开发时,会遇到对Json字符串解析的问题,这时我们想到的是创建一个Model类来进行数据解析,但有时候Json字符串比较复杂,层次较多,手动创建的话会稍显繁琐,这时就可以利用VS的一个功能(下面的案例用的是vs2015):
1.复制Json字符串,如下:

{"path":"C:\\Users\\Administrator\\Desktop\\TestImage\\heshui-013.jpg","outputs":{"Object":[{"name":"花","polygon":null,"bndbox":{"X":242,"Y":368,"Width":994,"Height":437}},{"name":"鸟","polygon":null,"bndbox":{"X":356,"Y":1368,"Width":886,"Height":413}},{"name":"鱼","polygon":{"pointList":[{"IsEmpty":false,"X":2391.0,"Y":504.97},{"IsEmpty":false,"X":3487.05,"Y":320.0},{"IsEmpty":false,"X":4229.02,"Y":858.98}]},"bndbox":null},{"name":"虫","polygon":{"pointList":[{"IsEmpty":false,"X":2031.0,"Y":1265.0},{"IsEmpty":false,"X":3349.02,"Y":1025.0},{"IsEmpty":false,"X":4487.05,"Y":1175.0}]},"bndbox":null},{"name":"虫2","polygon":{"pointList":[{"IsEmpty":false,"X":571.0,"Y":2229.99},{"IsEmpty":false,"X":1751.0,"Y":2074.0},{"IsEmpty":false,"X":1343.99,"Y":2961.01}]},"bndbox":null}]},"time_labeled":1588835040757,"labeled":true,"size":{"width":5184,"height":3456,"depth":3}}

2.在C#项目中新建一个类文件JsonModel.cs(或任意打开一个.cs文件)
根据Json字符串创建C#的Model类_第1张图片
3.一次点击菜单栏里面的 “编辑”–“选择性粘贴”–“将Json粘贴为类”
根据Json字符串创建C#的Model类_第2张图片
4.然后就可以在JsonModel.cs(上面打开的.cs文件)里面看到新创建的类了

public class Rootobject
    {
        public string path { get; set; }
        public Outputs outputs { get; set; }
        public long time_labeled { get; set; }
        public bool labeled { get; set; }
        public Size size { get; set; }
    }

    public class Outputs
    {
        public Object[] Object { get; set; }
    }

    public class Object
    {
        public string name { get; set; }
        public Polygon polygon { get; set; }
        public Bndbox bndbox { get; set; }
    }

    public class Polygon
    {
        public Pointlist[] pointList { get; set; }
    }

    public class Pointlist
    {
        public bool IsEmpty { get; set; }
        public float X { get; set; }
        public float Y { get; set; }
    }

    public class Bndbox
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
    }

    public class Size
    {
        public int width { get; set; }
        public int height { get; set; }
        public int depth { get; set; }
    }

5.用新建的类进行数据测试_序列化
测试代码:

private void ModelClassTest()
{
    var fileName = @"C:\Users\Administrator\Desktop\Test\heshui-013.json";
    using (var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read))
    {
        using (var sr = new StreamReader(fs,Encoding.Default))
        {
            var jsonStr = sr.ReadToEnd();
            var rootObj = JsonConvert.DeserializeObject(jsonStr);
            return;
        }
    }
}

测试结果:
根据Json字符串创建C#的Model类_第3张图片
说来惭愧,我也是最近遇到问题, 请教了大神才知道vs有这个功能…感谢大神

你可能感兴趣的:(.Net技术,c#,json)