c# - 将C#对象序列化为json

标签 c# json serialization json.net

创建可序列化为的 C# 类的最佳方法是什么:

marks:          [
             { c: [57.162499, 65.54718], // latitude, longitude - this type of coordinates works only for World Map
               tooltip: 'Tyumen - Click to go to http://yahoo.com', // text for tooltip
               attrs: {
                        href: 'http://yahoo.com',            // link
                        src:  '/markers/pin1_red.png'        // image for marker
                       }
             },
             { xy: [50, 120], // x-y coodinates - works for all maps, including World Map
               tooltip: 'This is London! Click to go to http://london.com',
               attrs: {
                        href: 'http://yahoo.com',            // link
                        src:  '/markers/pin1_yellow.png'     // image for marker
                       }
             }
            ]

在上面的代码中,我们分配“c”或“xy”,但不能同时分配两者。 我正在使用 Newtonsoft.Json。 我唯一想要的是一个可以序列化为上面代码的 C# 类。

最佳答案

该类如下所示:

[Serializable]
public class Marks
{
    public List<latlon> marks = new List<latlon>();
}

public class latlon
{
    public double[] c;
    public int[] xy;
    public string tooltip;
    public attributes attrs;

    public latlon (double lat, double lon)
    {
        c = new double[] { lat, lon };
    }
    public latlon (int x, int y)
    {
        xy = new int[] { x, y };
    }
}

public class attributes
{
    public string href;
    public string src;
}

测试它的代码如下所示:

string json;

Marks obj = new Marks();
latlon mark = new latlon(57.162, 65.547)
    {
        tooltip = "Tyumen - Click to go to http://yahoo.com",
        attrs = new attributes()
        {
            href = "http://yahoo.com",
            src = "/markers/pin1_red.png"
        }
    };

obj.marks.Add(mark);

mark = new latlon(50, 120)
    {
        tooltip = "This is London! Click to go to http://london.com",
        attrs = new attributes()
        {
            href = "http://yahoo.com",
            src = "/markers/pin1_yellow.png"
        }
    };

obj.marks.Add(mark);

//serialize to JSON, ignoring null elements
json = JsonConvert.SerializeObject(obj, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

关于c# - 将C#对象序列化为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11987675/

相关文章:

c# - C# Windows 服务的安全性

json - Swift,当 key 未知/动态时,如何使用 Decodable 和 Codable 解析/解码 JSON

c# - 在 C# 中序列化嵌套类?

java - 反序列化 bean 需要范围依赖

c# - 无法在 Unity 项目上添加 EasyNetQ 的引用

c# - 为什么 LINQ 扩展以非常难以阅读的方式编写?

c# - 将int转换为int?可能的更新?

json - 指导如何实际加密 APNS 的 JSON token

ios - 无法调用“jsonObjectWithData”

xml - 从 WCF Restful 响应中删除 xml 命名空间