简体   繁体   English

属性强类型以松散类型JSON序列化

[英]Property strongly type to loosely typed JSON serialize

I'm working on a MVC project using C# and have controller method that returns a JsonResult model. 我正在使用C#进行MVC项目,并且具有返回JsonResult模型的控制器方法。 The model contains a property called Value. 该模型包含一个名为Value的属性。

Based on certain conditions the Value maybe a string value such as "C" or "N". 根据某些条件,值可能是字符串值,例如“ C”或“ N”。 But under other conditions it maybe .5. 但在其他情况下,可能是0.5。

When serializing the Model is it possible to check and if the property is a numeric to serialize it as number (no quotes)? 序列化模型时,是否可以检查属性是否为数字以序列化为数字(无引号)? If it is not a number then make it a string (quotes)? 如果不是数字,则将其设为字符串(引号)?

For example I have the following class: 例如,我有以下课程:

public class Answer
{
   public int Id{get;set;}
   public string Value { get; set; }
}

Let's say I return a list of these back: I'd like to have something like below: (Notice the 1st answer the "value" is not quoted; however, the 2nd and 3rd answer are quoted. 假设我返回了这些列表:我想像下面这样:(请注意,第一个答案的“值”没有被引用;但是,第二个和第三个答案被引用了。

{
    "answers": [
        {
           "id": 1,
           "value": .5 <- No quote here.
        },
        {
           "id": 1,
           "value": "C" <- Quote here
        },
        {
           "id": 1,
           "value": "N" <- Quote here
        }
     ]
}

When it comes back server side (de-serializing), I'd just like the string representation. 回到服务器端(反序列化)时,我只需要字符串表示形式。

I think you will have to implement a custom JSON Converter. 我认为您将必须实现自定义JSON转换器。 See the following link: 请参阅以下链接:

http://james.newtonking.com/json/help/index.html?topic=html/CustomJsonConverter.htm http://james.newtonking.com/json/help/index.html?topic=html/CustomJsonConverter.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM