如何使用Newtonsoft反序列化一组对象数组

时间:2016-10-05 18:12:12

标签: c# json json.net deserialization json-deserialization

我试图像这样反序列化一个Object。 我的问题是它正试图将内部项目反序列化。

{
    "outeritems": [{        
        "inneritems": [
            [{
                "itemid": "1"                
            }, {
                "itemid": "2"                
            }]
        ]
    }]    
}

我已经尝试了

public List<List<inneritems>> inneritems{ get; set; }

public List<inneritems> inneritems{ get; set; }

我认为这可能需要自定义JSON转换器

3 个答案:

答案 0 :(得分:1)

事实上,vikas已经接近你的问题了。

public class Outeritem
    {
        public List<List<object>> inneritems { get; set; }
    }

    public class RootValue
    {
        public List<Outeritem> outeritems { get; set; }
    }

    [TestMethod]
    public void SerializeAndDeserializeTest()
    {
        var expected = "{\"outeritems\":[{\"inneritems\":[[{\"itemid\":\"1\"},{\"itemid\":\"2\"}]]}]}";
        var rootValue = new RootValue
        {
            outeritems = new List<Outeritem>
            {
                new Outeritem
                {
                    inneritems = new List<List<object>> {
                        new List<object> { new {itemid = "1"},new {itemid = "2"} }
                    }
                }
            }
        };

        var actual = JsonConvert.SerializeObject(rootValue);
        Assert.AreEqual(expected, actual);
    }

答案 1 :(得分:0)

试试这个

public class Inneritem
{
    public String itemid { get; set; }
}

public class Outeritem
{
    public List<Inneritem> inneritems { get; set; }
}

public class RootValue
{
    public List<Outeritem> outeritems { get; set; }
}

答案 2 :(得分:-2)

我必须创建一个自定义的Newtonsoft JSON Converter

这就是我所做的。

创建了一个JsonCreationConverter基类

public abstract class JsonCreationConverter<T> : JsonConverter
{        
    protected abstract T Create(Type objectType, JObject jObject);

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException("Unnecessary because CanWrite is false. The type will skip the converter.");
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        JObject jObject = JObject.Load(reader);           

        T target = Create(objectType, jObject);

        // Populate the object properties
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(T).IsAssignableFrom(objectType);
    }

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

创建了继承我的基类

的服装转换器
public class OuterConverter :
        JsonCreationConverter<OuterItems>
{
        protected override OuterItems Create(Type objectType, JObject jObject)
        {
            OuterItems outeritems =
                new OuterItems();

            var properties = jObject.Properties().ToList();
            outeritems.InnerItems = GetInnerItems((object)properties[0].Value);

            return outeritems;
        }

        // Need to iterate through list so creating a custom object
        private List<List<InnerItems>> GetInnerItems(object propertyValue)
        {

            string sinneritems = "";
            object inneritems = propertyValue;
            sinneritems = String.Format("{0}", inneritems);

            sinneritems = sinneritems.Insert(1, "{ \"Items\": [");
            sinneritems = sinneritems.Substring(1, sinneritems.Length - 1);
            sinneritems = sinneritems.Remove(sinneritems.Length - 1);

            sinneritems += "]}";

            dynamic results = JObject.Parse(sinneritems);

            List<List<InnerItems>> innerItemsList = new List<List<InnerItems>>();

            List<InnerItems> linnerItems = new List<InnerItems>();

            foreach (var items in results.Items)
            {
                foreach (var item in items)
                {
                    string sItem = String.Format("{0}", item);
                    InnerItems ninneritems = Newtonsoft.Json.JsonConvert.DeserializeObject<InnerItems>(sItem);
                    linnerItems.Add(ninneritems);
                }
                innerItemsList.Add(linnerItems);
            }

            return innerItemsList;
        }
}

在Newtonsoft Deserializer

上附加新转换器
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(result.ToString(),
             new OuterConverter());