简体   繁体   English

反序列化期间或之后验证和纠正JSON数据

[英]Validating and Correcting JSON data during or after deserialization

I have been agonizing over this problem for a few days now and have no hope left. 我已经为这个问题苦恼了几天,没有希望了。 I'm still in the early stages of learning C#, so excuse me if my explanations or understanding are lacking. 我仍处于学习C#的早期阶段,因此,如果缺少我的解释或理解,请原谅。

My scenario is that I have a need to access an API and download the data as JSON then deserialize it into a class. 我的情况是,我需要访问一个API并以JSON格式下载数据,然后将其反序列化为一个类。 At the moment, things work as they should, however every variable is defined as String which means I need to convert and manipulate data that should be int/double on the fly constantly as the API can give "N/A" for these data. 目前,一切正常,但是每个变量都定义为String,这意味着我需要不断地转换和操作应为int / double的数据,因为API可以为这些数据提供“ N / A”。 The impression I get is relying on everything being string is bad practice. 我得到的印象是依靠一切都是字符串,这是不好的做法。

So how should I implement it? 那么我应该如何实施呢? I need to be able to store the data as the correct type while keeping in mind that it could be wrong. 我需要能够将数据存储为正确的类型,同时要记住这可能是错误的。

Example of properties with wrong type 类型错误的属性示例

public string Title { get; set; }
public string Year { get; set; } // Wanted int. Often has an end year "2010-2014"
public string Metascore { get; set; } // Wanted double. Could be "N/A"

The only way I can imagine solving this is by having two classes: the first one being the original string-only class, then having the second being an almost identical class with the desired properties that uses the data from the original then converts it. 我可以想象解决此问题的唯一方法是拥有两个类:第一个是原始的仅字符串类,然后第二个是几乎相同的类,具有使用原始数据的所需属性,然后将其转换。

My problem with that is that the class already has a few dozen properties, so duplicating it seems nearly as wasteful as the original problem. 我的问题是该类已经具有几十个属性,因此复制它似乎和原始问题一样浪费。 Regardless, I would like to know an alternative for future use anyway. 无论如何,我还是想知道一种可供将来使用的替代方法。

EDIT: Found a similar question here , though unfortunately it didn't help. 编辑: 在这里找到一个类似的问题,虽然不幸的是它没有帮助。

you can deserialize the json to JObject and than load it your self 您可以将json反序列化为JObject ,然后自行加载

public class RootObject
    {
        public RootObject(JObject obj)
        {
            Title = obj["Title"].ToString();
            var year = obj["year"].ToString();
            Year = year == "N/A" ? 0 : int.Parse(year);
            var metascore = obj["Metascore"].ToString();
            Metascore = metascore == "N/A" ? 0 : int.Parse(metascore);
        }

        public string Title { get; set; }
        public int Year { get; set; } 
        public double Metascore { get; set; } 
    }

    static void Main(string[] args)
    {
        string json = "{\"Title\":\"test\",\"year\":\"2012\",\"Metascore\":\"N/A\"}";
        RootObject root = new RootObject(JObject.Parse(json));
    }

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

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