相关疑难解决方法(0)

JSON序列化缺少派生类中的属性

我正在使用Newtonsoft JSON序列化程序,如果类是从列表派生的,则序列化字符串缺少派生类的属性.这是我的示例代码.

类别:

[DataContract]
public class TestItem
{
    [DataMember]
    public int itemInt;
    [DataMember]
    public string itemString;

    public TestItem() {}
    public TestItem(int _intVal, string _stringVal)
    {
        itemInt = _intVal;
        itemString = _stringVal;
    }
}

[DataContract]
public class TestMain : List<TestItem>
{
    [DataMember]
    public int mainInt;
    [DataMember]
    public string mainString;
}
Run Code Online (Sandbox Code Playgroud)

序列化代码:

string test;

// Test classes
TestMain main = new TestMain();
main.mainInt = 123;
main.mainString = "Hello";
main.Add(new TestItem(1, "First"));

test = Newtonsoft.Json.JsonConvert.SerializeObject(main);
Run Code Online (Sandbox Code Playgroud)

序列化后,test的值为:

[{\ "itemInt \":1,\ "itemString \":\ "第一\"}]

mainInt和mainString的值完全缺失. …

c# json

7
推荐指数
1
解决办法
1720
查看次数

使用[JsonConvert()]时,JSON.Net抛出StackOverflowException

我将这个简单的代码编写为Serialize类为flatten,但是当我使用[JsonConverter(typeof(FJson))]注释时,它会抛出StackOverflowException.如果我SerializeObject手动调用它,它工作正常.

如何在注释模式下使用JsonConvert:

class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.id = 1;
            a.b.name = "value";

            string json = null;

            // json = JsonConvert.SerializeObject(a, new FJson()); without [JsonConverter(typeof(FJson))] annotation workd fine
            // json = JsonConvert.SerializeObject(a); StackOverflowException

            Console.WriteLine(json);
            Console.ReadLine();
        }
    }

    //[JsonConverter(typeof(FJson))] StackOverflowException
    public class A
    {
        public A()
        {
            this.b = new B();
        }

        public int id { get; set; }
        public string name { get; set; }
        public …
Run Code Online (Sandbox Code Playgroud)

c# serialization json json.net

3
推荐指数
4
解决办法
7266
查看次数

如何使用 Json.NET 将根节点添加到 C# 中的 JSON?

我正在处理Visual Studio C#项目,我需要将 a 转换JSONXML. 我收到JSON字符串格式的。问题是,JSON如果JSON没有根节点,我需要在结构中有一个根节点,以便我可以转换为XML所需的格式。

假设我有这个JSON

{
        "id": 1,
        "name": {
            "first": "Yong",
            "last": "Mook Kim"
        },
        "contact": [{
            "type": "phone/home",
            "ref": "111-111-1234"
        }, {
            "type": "phone/work",
            "ref": "222-222-2222"
        }]
}
Run Code Online (Sandbox Code Playgroud)

我想像这样添加根节点JSON

{
    "user": {
        "id": 1,
        "name": {
            "first": "Yong",
            "last": "Mook Kim"
        },
        "contact": [{
            "type": "phone/home",
            "ref": "111-111-1234"
        }, {
            "type": "phone/work",
            "ref": "222-222-2222"
        }]
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能用 …

c# json json.net

2
推荐指数
1
解决办法
6654
查看次数

标签 统计

c# ×3

json ×3

json.net ×2

serialization ×1