Newtonsoft Json List 序列化返回 $id

我正在 C# 中开发一个 API,它使用 Newtonsoft.Json 将 C# 类序列化为 json 并且我有一个非常奇怪的行为,使用以下方法序列化“GetInputStatesResponse”下面的类

JsonConvert.SerializeObject(response)

public class GetInputStatesResponse     
{
    public List<InputKeyValue> InputStates { get; set; } = new List<InputKeyValue>();
}
    
public class InputKeyValue 
{   
    public InputKey Key { get; set; }
    public int Value { get; set; }
}

InputKey 属性是一个枚举。

当我序列化一个 'GetInputStatesResponse 时,我得到以下 Json :

{
  "InputStates":[
    {"$id":"1"},{"$id":"2"}
  ]
} 

我想我应该得到更多这样的东西:

{
  "InputStates": [  
    { Key:"Safe_Closed",Value: 0 },{ Key:"GateFront_Closed",Value: 1 }
  ]
}

知道我没有得到正确序列化输出的原因吗?

lihonglian26 回答:Newtonsoft Json List 序列化返回 $id

我刚刚发现 InputKeyValue 类继承了一些具有以下属性的内部类

[DataContract(IsReference = true)]

删除继承或属性解决了问题:)

本文链接:https://www.f2er.com/29061.html

大家都在问