JSON反序列化类型不支持数组的反序列化 [英] JSON Deserialization Type is not supported for deserialization of an array

查看:3725
本文介绍了JSON反序列化类型不支持数组的反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过关于反序列化错误另外两个职位,但我没有得到任何地方,所以我张贴我自己的问题。



我有一个返回的JSON的WCF服务。在特定类型的反序列化,它失败。



在努力让你轻松复制错误,我硬编码下面的JSON与呼叫一起。



从本质上讲,你应该能够复制/粘贴下面的代码,看看它是失败的。



消费者需要反序列化到一个工作对象这一点。 s.Deserialize失败,并在标题提到的错误信息



注:我知道有斜杠在我的JSON。这些都是有为了方便逃跑的报价。谢谢



示例代码:

  VAR小号=新的JavaScriptSerializer(); 

变种jstr =
[{\UserId\:1,\WorkoutId\:1,\WorkoutInfo\:\步骤1\,\步骤2\]},{\UserId\:2,\WorkoutId\:2,\WorkoutInfo\:\步骤1a\,\步骤2a\]},{\UserId\:5,\WorkoutId\:0,\WorkoutInfo\:\新work1\,\新作1\,\新作1\]}];

锻炼等等= s.Deserialize<健身及GT;(jstr);
VAR响应= ServicePOST<健身及GT;(AddUserWorkout,锻炼);

和锻炼类:

 公共类锻炼
{
公众诠释用户ID {搞定;组; }
公开名单<串GT; WorkoutInfo {搞定;组; }
}


解决方案

的问题是,你'再告诉这只是一个单一的锻炼,而不是一个列表/人阵串行。这工作:

  VAR等等= s.Deserialize<名单,LT;健身及GT;>(jstr); 

这是不直接关系到你的问题,但如果可能的话,我建议您使用 Json.NET 而不是的JavaScriptSerializer


I've read two other posts regarding the deserialization error, but I've not gotten anywhere so I'm posting my own question.

I have a WCF service that's returning JSON. Upon deserialization of a specific type, it fails.

In an effort to allow you to easily replicate the error, I've hardcoded the JSON below along with the call.

Essentially you should be able to copy/paste the code below and see it fail.

The consumer needs to deserialize this into a working object. s.Deserialize fails with the error message noted in the Title.

NOTE: I realize there are slashes in my JSON. Those are there for convenience to escape the quotes. Thanks.

Example code:

  var s = new JavaScriptSerializer();

        var jstr =
            "[{\"UserId\":1,\"WorkoutId\":1,\"WorkoutInfo\":[\"Step 1\",\"Step 2\"]},{\"UserId\":2,\"WorkoutId\":2,\"WorkoutInfo\":[\"Step 1a\",\"Step 2a\"]},{\"UserId\":5,\"WorkoutId\":0,\"WorkoutInfo\":[\"new work1\",\"new work 1\",\"new work 1\"]}]";

        Workout blah = s.Deserialize<Workout>(jstr);
        var response = ServicePOST<Workout>("AddUserWorkout", workout);

and Workout class:

public class Workout
{
    public int UserId { get; set; }
    public List<string> WorkoutInfo { get; set; }
}

解决方案

The problem is that you're telling the serializer that it's just a single Workout, not a list/array of them. This works:

var blah = s.Deserialize<List<Workout>>(jstr);

This isn't directly related to your question, but if at all possible, I'd recommend that you use Json.NET instead of JavaScriptSerializer.

这篇关于JSON反序列化类型不支持数组的反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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