我正在使用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的值完全缺失. …
我将这个简单的代码编写为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) 我正在处理Visual Studio
C#
项目,我需要将 a 转换JSON
为XML
. 我收到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)
我怎样才能用 …