JSON反序列化为类,缺少json中的键[字符串可以是单个字符串或列表字符串] [英] JSON deserialize to class with missing key in json [string could be a single string or list string]

查看:127
本文介绍了JSON反序列化为类,缺少json中的键[字符串可以是单个字符串或列表字符串]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下课上

    [Serializable]
    public class filters
    {
        public List<string> key1 { get; set; }
        public List<string> key2 { get; set; }
        public List<string> key3 { get; set; }
    }

并且json字符串是

[{"key1": "key1value"}]

反序列化

filters objFilter = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<filters>(json);

json字符串可以包含key1,key2和key3,也可以不包含.

json string may contain key1, key2 and key3 or may not.

key1,key2,key3可以是单个字符串或数组

key1, key2, key3 may be a single string or array

那么我该如何反序列化.

So how can i deserialize it.

主要是抛出错误.

数组反序列化不支持

class

class is not supported for deserialization of an array

请告知 谢谢

推荐答案

您的代码存在问题,因为您的json不正确

The problem with your code is your json is incorrect

在控制台应用程序中获取以下代码,然后查看获得的结果

Take the following code in a console app and see what you get

var filtr = new filters { key1 = new List<string>() { "key1value" } };
var json = new JavaScriptSerializer().Serialize(filtr);
var text = "{\"key1\":[\"key1value\"]}";
filtr = new JavaScriptSerializer().Deserialize<filters>(text);

或仅将json更改为以下

Or change your json just to the following

json中的[[]"表示它是一个数组,因此您尝试对数组进行反序列化以键入过滤器

The '[]' in your json is a represenation that it it is an array, so you are trying to deserialize an array to type filters

{"key1":["key1value"]}

然后您的反序列化应该起作用

then your deserialize should work

这篇关于JSON反序列化为类,缺少json中的键[字符串可以是单个字符串或列表字符串]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆