简体   繁体   English

反序列化用引号括起来的 JSON 字符串

[英]Deserializing JSON string surrounded with quotes

Is there a way to correctly deserialize a JSON string that begins and ends with double quotes?有没有办法正确反序列化以双引号开头和结尾的 JSON 字符串?

This is the contents of the stream being read from a file:这是从文件中读取的流的内容:

"[{\"startTime\":1610396717400,\"eventCode\":44,\"eventParam\":5},{\"startTime\":1610396717700,\"eventCode\":81,\"eventParam\":56},{\"startTime\":1610396717800,\"eventCode\":44,\"eventParam\":4}"

The JsonSerializer does not seem to deserialize this properly. JsonSerializer 似乎没有正确反序列化。 However, for a JSON file with the following contents, it works as expected:但是,对于具有以下内容的 JSON 文件,它按预期工作:

[{"startTime":1610396717400,"eventCode":44,"eventParam":5},{"startTime":1610396717700,"eventCode":81,"eventParam":56}]

This is the snippet:这是片段:

public class ControllerEventJson
{
    [JsonProperty("startTime")]
    public long StartTime { get; set; }

    [JsonProperty("eventCode")]
    public int EventCode { get; set; }

    [JsonProperty("eventParam")]
    public int EventParam { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        using (Stream stream = File.Open("test.json", FileMode.Open))
        using (StreamReader sr = new StreamReader(stream))
        using (JsonTextReader reader = new JsonTextReader(sr))
        {
            // Required for large JSON objects to avoid errors when streaming
            reader.SupportMultipleContent = true;

            JsonSerializer serializer = new JsonSerializer();
            while (reader.Read())
            {
                // Deserialize each object in array individually
                if (reader.TokenType == JsonToken.StartObject)
                {
                    var obj = serializer.Deserialize<ControllerEventJson>(reader);
                    // Do something with obj
                }
            }
        }
    }
}

Well, I mean, if you just want to take out the quotation marks at the start and end, then you can check for it and just remove them artificially and explicitly before reading it with the StreamReader.好吧,我的意思是,如果您只想去掉开头和结尾的引号,那么您可以检查它并在使用 StreamReader 读取它之前人为地显式删除它们。 Something like this:像这样的东西:

        string fileName = @"c:\temp\test.json";
        string data = File.ReadAllText(fileName);
        string newFileName = "";
        //If quotation marks are at the start or end, then remove them
        if (data.StartsWith(@"""") || data.EndsWith(@""""))
        {
            newFileName = Path.GetTempFileName();
            using (StreamWriter sw = new StreamWriter(newFileName))
            {
                sw.Write(data.Trim('"'));
            };
        }

        using (Stream stream = File.Open(newFileName != "" ? newFileName : fileName, FileMode.Open))
        using (StreamReader sr = new StreamReader(stream))
        using (JsonTextReader reader = new JsonTextReader(sr))
        {
            // Required for large JSON objects to avoid errors when streaming
            reader.SupportMultipleContent = true;

            JsonSerializer serializer = new JsonSerializer();
            while (reader.Read())
            {
                // Deserialize each object in array individually
                if (reader.TokenType == JsonToken.StartObject)
                {
                    //do stuff
                }
            }
        }

        if (newFileName != "") File.Delete(newFileName); //Clean up after yourself

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

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