C# - 将json反序列化为对象 [英] C#- deserialize json to object

查看:562
本文介绍了C# - 将json反序列化为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..我有一个json序列化的问题,它会抛出错误:

无法从System.String转换或转换为System.Collections.Generic.IList `1 [System.String]。]。

我的json:{\Type \:\abc \,\Filepath \:\D:\\\\ abc.doc\ };
我的班级:
公共类参数{public string Type {get;组; }
public IList Filepath {get;组;
我的反序列化代码:
var jsonObj = new JavaScriptSerializer()。Deserialize(json);

你能帮我理解这个问题吗?我把它列为一个列表,因为可能有接收多个对象的情况,因此它是必需的。如果你可以帮助我会很棒!

当我有多个值时它工作正常,即:
{\Type \:\abc \,\Filepath \:[ \ d:\\\\abc1.doc\,\ d:\\\\abc2.doc\]};
我希望它在两个方面都能很好地工作。





我尝试过: <我需要反序列化代码:
var jsonObj = new JavaScriptSerializer()。Deserialize(json);


我的反序列化代码:
var jsonObj = new JavaScriptSerializer()。

解决方案

好的,这个

 {
类型:abc,
文件路径:D:\\abc.doc
}



反序列化为:

  public   class 示例
{
public string 输入{ get ; set ; }
public string 文件路径{ get ; set ; }
}



这个

 {
Type:abc ,
文件路径:[D:\\abc1.doc,D:\\abc2.doc]
}



反序列化:

  public   class 示例
{
public string 类型{获得; set ; }
public IList< string> Filepath { get ; set ; }
}



所以你看到的错误:

无法投射或从System.String转换为System.Collections.Generic.IList`1 [System.String]。]。



现在应该有更多含义。所以你不能反序列化:

 {
Type:abc,
Filepath :D:\\ abc.doc
}



到此:

  public   class 示例
{
public string 输入{ get ; set ; }
public IList< string> Filepath { get ; set ; }
}



有关使用反序列化JSON的更多信息,请查看以下文章:在C#中使用JSON& VB [ ^ ]


这是一个糟糕的JSON架构。你必须使用 JSON.NET [ ^ ]带有自定义转换器来读取它。



此StackOverflow主题 [ ^ ]有一个例子:

  class  SingleOrArrayConverter< T> :JsonConverter 
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof (列表< T>));
}

public 覆盖 对象 ReadJson(JsonReader reader,Type objectType, object existingValue,JsonSerializer序列化程序)
{
JToken token = JToken。负载(读取器);
if (token.Type == JTokenType.Array)
{
return token.ToObject< List< T>>();
}
return new 列表< T> {token.ToObject< T>()};
}

public 覆盖 bool CanWrite
{
get { return < span class =code-keyword> false
; }
}

public 覆盖 void WriteJson(JsonWriter writer, object value ,JsonSerializer序列化程序)
{
列表< T> list =(List< T>) value ;
if (list.Count == 1
{
value = list [ 0 ];
}
serializer.Serialize(writer, value );
}
}

...

[JsonConverter( typeof (SingleOrArrayConverter< string>))]
public List< string> Filepath { get ; set ; }


Hi..I have an issue with json serialization which throws the error: 

"Could not cast or convert from System.String to System.Collections.Generic.IList`1[System.String].]".
 
My json: "{\"Type\": \"abc\",\"Filepath\": \"D:\\\\abc.doc\"}"; 
My class: 
public class Arguments { public string Type { get; set; } 
public IList Filepath { get; set; } } 
My code to deserialize: 
var jsonObj = new JavaScriptSerializer().Deserialize(json); 

Can you help me understand the issue? I have made it a list as there can be situation to receive multiple objects and hence it is required. Would be great if you can help me!

It works fine when i have multiple values, ie:
 "{\"Type\": \"abc\",\"Filepath\": [\"D:\\\\abc1.doc\",\"D:\\\\abc2.doc\"]}";
I want it to work fine in both ways.



What I have tried:

My code to deserialize: 
var jsonObj = new JavaScriptSerializer().Deserialize(json); 

解决方案

Okay, this

{
    "Type": "abc",
    "Filepath": "D:\\abc.doc"
}


deserializes to this:

public class Example
{
    public string Type { get; set; }
    public string Filepath { get; set; }
}


And this

{
    "Type": "abc",
    "Filepath": ["D:\\abc1.doc","D:\\abc2.doc"]
}


deserializes to this:

public class Example
{
    public string Type { get; set; }
    public IList<string> Filepath { get; set; }
}


So the error that you are seeing:

"Could not cast or convert from System.String to System.Collections.Generic.IList`1[System.String].]".


Should now have more meaning. So you can not deserialize this:

{
    "Type": "abc",
    "Filepath": "D:\\abc.doc"
}


to this:

public class Example
{
    public string Type { get; set; }
    public IList<string> Filepath { get; set; }
}


For more information on working with deserializing JSON, check out this article: Working with JSON in C# & VB[^]


That's a terrible JSON schema. You'll have to use JSON.NET[^] with a custom converter to read it.

This StackOverflow thread[^] has an example:

class SingleOrArrayConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>();
        }
        return new List<T> { token.ToObject<T>() };
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        List<T> list = (List<T>)value;
        if (list.Count == 1)
        {
            value = list[0];
        }
        serializer.Serialize(writer, value);
    }
}

...

[JsonConverter(typeof(SingleOrArrayConverter<string>))]
public List<string> Filepath { get; set; }


这篇关于C# - 将json反序列化为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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