简体   繁体   English

在C#中反序列化json数组列表

[英]deserialize json array list in c#

I'm working on a project which has as backend mainly C#, but I'm not an experienced C# dev so I'm not able to figure out hot to fix a json deserialization of an list of objects. 我正在从事一个主要具有C#后端的项目,但是我不是一个经验丰富的C#开发人员,因此我无法弄清楚修复对象列表的json反序列化的方法。 The following function is what takes care of the deserialization, but I get an error : 以下函数负责反序列化,但出现错误:

using System.IO;
using System.Web;
using Raven.Imports.Newtonsoft.Json;

namespace Corina.Web.Handlers
{
    public class JsonRequestHandler
    {
        public T Handle<T>(HttpContextBase context)
        {
            string requestData;

            context.Request.InputStream.Position = 0;
            using (var inputStream = new StreamReader(context.Request.InputStream))
            {
                requestData = inputStream.ReadToEnd();
            }

            return JsonConvert.DeserializeObject<T>(requestData, new Raven.Imports.Newtonsoft.Json.Converters.StringEnumConverter());           
        }
    }
}

Error : Error

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'Corina.Web.Views.DocumentViewModel' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly. 无法将当前JSON数组(例如[1,2,3])反序列化为类型'Corina.Web.Views.DocumentViewModel',因为该类型需要JSON对象(例如{“ name”:“ value”})才能正确反序列化。

To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. 要解决此错误,可以将JSON更改为JSON对象(例如{“ name”:“ value”}),也可以将反序列化类型更改为数组,或者将实现集合接口的类型(例如ICollection,IList)更改为List,例如List从JSON数组反序列化。 JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. 还可以将JsonArrayAttribute添加到类型中,以强制其从JSON数组反序列化。

Can anyone tell me how do I make the deserialization on a list of objects instead of an object ? 谁能告诉我如何对对象列表而不是对象进行反序列化?

You have to create this class and create a method like below : 您必须创建此类并创建如下方法:

   public class Demo
   {
      public string Name;
      public string Type;
      public string Value;
      public string ChildContentType;
      public string ChildMetadata;
   }

    public void Deserialize()
    {
        string jsonObjString = "[{\"Name\": \"Description\",\"Type\": \"Text\",\"Value\": \"XXX\",\"ChildContentType\": \"Value\",\"C??hildMetadata\": \"YYY\"}]";
         var ser = new JavaScriptSerializer();
         var arreyDemoObj = ser.Deserialize<Demo[]>(jsonObjString);

         foreach (Demo objDemo in arreyDemoObj)
         {
             //Do what you want with objDemo
         }
      }

Note that you need to add reference for JavaScriptSerializer . 请注意,您需要添加对JavaScriptSerializer的引用。

Don't know the structure of your json data but i guess you are using some custom classes to deserialize with DataContractJsonSerializer you can deserialize in the following manner 不知道您的json数据的结构,但我想您正在使用一些自定义类通过DataContractJsonSerializer反序列化,您可以按以下方式反序列化

Json list: 杰森清单:

var testdata = "[{\"name\":\"numToRetrieve\",\"value\":\"3\",\"label\":\"Number of     items       to retrieve:\"},{\"name\":\"showFoo\",\"value\":\"on\",\"label\":\"Show foo?\"},  {\"name\":\"title\",\"value\":\"Foo\",\"label\":\"Foo:\"}]";

DataContractJsonSerializer js = 
new DataContractJsonSerializer(typeof (List<FooDef>));
var stream = new MemoryStream(Encoding.UTF8.GetBytes(testdata));
var foo = js.ReadObject(stream);
stream.Close();



[DataContract]
public sealed class FooDef
{
    [DataMember(Name = "name", IsRequired = true)]
    public string Name { get; set; }

    [DataMember(Name = "value", IsRequired = true)]
    public string Value { get; set; }

    [DataMember(Name = "label", IsRequired = true)]
    public string Label { get; set; }
} 

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

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