简体   繁体   English

如何反序列化JSON字符串不列出 <object> 在C#中

[英]How to deserialize json string NOT to List<object> in c#

i'm working with Vk.com api, in particular with this json string: 我正在使用Vk.com api,尤其是使用以下json字符串:

{
"response":
[338775,
{"aid":108787020,
"owner_id":2373452,
"artist":" Moby",
"title":"Flowers",
"duration":208,
"url":"https:\/\/cs1-50v4.vk-cdn.net\/p3\/c762273870cc49.mp3?extra=t9I-RMkSlAHkhe8JtOUUZBTZqkFVE9MJ_Q-TPmOhxPHTfHazQWEYBf4LqrOY64xLX9AuzaKwvLo4PECSFiHyWM53WMDWVcBAZVT5jlIbZ9X8ag","lyrics_id":"6060508",
"genre":22}
]
}

I have a class for parsing data: 我有一个解析数据的类:

public class AlbumResponse
    {
        [JsonProperty("artist")]
        public string artist { get; set; }
        [JsonProperty("title")]
        public string title { get; set; }
        [JsonProperty("duration")]
        public string duration { get; set; }
        [JsonProperty("url")]
        public string url { get; set; }
    }

And List for deserialization: 以及反序列化列表:

public class VkAlbum
{
    public List<AlbumResponse> response { get; set; }
}

Than I use 比我用

var album = JsonConvert.DeserializeObject<VkAlbum>(responseText);

BUT it doesn't work (A first chance exception of type 'Newtonsoft.Json.JsonSerializationException') because of "338775" after "response". 但是由于“响应”之后的“ 338775”,它不起作用(类型为“ Newtonsoft.Json.JsonSerializationException”的第一次机会异常)。 So how can I deserialize it without using 所以我如何不使用它反序列化

 public List<object> response { get; set; }

instead of my AlbumResponse class? 而不是我的AlbumResponse类?

A primitive JSON sanitation for your disposal. 原始的JSON卫生供您处理。 Not the most elegant code, but i'm sure you can take it from here. 不是最优雅的代码,但是我敢肯定您可以从这里获取。

responseText = Regex.Replace(responseText, "[\t|\r\n]", "");
if (responseText.IndexOf("response\": [") != -1)
{
    int start = responseText.IndexOf('[') + 1;
    int end = responseText.IndexOf(',', start);
    responseText = responseText.Substring(0, start) + responseText.Substring(end + 1);
}
var album = JsonConvert.DeserializeObject<VkAlbum>(responseText);

technically json response is not equivalent to C# List<AlbumResponse> . 从技术上讲json响应不等同于C# List<AlbumResponse> JSON array allows mixed types so essentially it can contains numbers and other nested objects, in your case AlbumResponse . JSON数组允许混合类型,因此从本质AlbumResponse它可以包含数字和其他嵌套对象,在您的情况下为AlbumResponse

you can avoid exception by using List<object> and checking it's first element if it's number, if it is, ignore or do whatever you want to do and typecast 2nd element in list to AlbumResponse . 您可以通过使用List<object>并检查它的第一个元素(如果是数字)来避免异常,如果它是数字,则忽略或执行任何您想做的事情,并将列表中的第二个元素AlbumResponseAlbumResponse

eg 例如

var res = response [1] as AlbumResponse;
if(res!=null)
{
    // do something interesting...

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

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