Pawan
Pawan

Reputation: 32321

Cannot deserialize json result to custom list object using c#

I have the below JSON:

{"positions":{"position":[{"cost_basis":102.20000,"date_acquired":"2013-11-18T19
:54:13.730Z","id":192,"quantity":2.00000,"symbol":"C"},{"cost_basis":121.50990,"
date_acquired":"2013-11-20T17:43:41.737Z","id":199,"quantity":1.00000,"symbol":"
TSLA"}]}}

I am using JSON.NET (Newtonsoft package) in order to deserialize to my data object.

List<position> position = JsonConvert.DeserializeObject<List<position>>(responsebody);
foreach (position item in listObj)
{
 Console.WriteLine("Test : ", item.id);
}


public class positions
    {
        List<position> position { get; set; }

    }

public class position
    {
        public float cost_basis { get; set; }
        public DateTime date_acquired { get; set; }
        public int id { get; set; }
        public int quantity { get; set; }
        public string symbol { get; set; }

    }

When I try to deserialize the object, I am getting the following error.

Unhandled Exception: Newtonsoft.Json.JsonSerializationException: Cannot deserial
ize the current JSON object (e.g. {"name":"value"}) into type 'System.Collection
s.Generic.List`1[ApiPost.position]' because the type requires a JSON array (e.g.
 [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or chang
e the deserialized type so that it is a normal .NET type (e.g. not a primitive t
ype like integer, not a collection type like an array or List<T>) that can be de
serialized from a JSON object. JsonObjectAttribute can also be added to the type
 to force it to deserialize from a JSON object.
Path 'positions', line 1, position 13.
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(Js
onReader reader, Type objectType, JsonContract contract, JsonProperty member, Js
onContainerContract containerContract, JsonProperty containerMember, Object exis
tingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInte
rnal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty mem
ber, JsonContainerContract containerContract, JsonProperty containerMember, Obje
ct existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(Jso
nReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type
 objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, Jso
nSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSeriali
zerSettings settings)

Upvotes: 2

Views: 11547

Answers (1)

Joey Gennari
Joey Gennari

Reputation: 2361

The JSON is valid, but you have an extra class that contains the list, so you'll need to break the class up like this:

public class positionsobj
{
    public positionlist positions { get; set; }
}

public class positionlist
{
    public List<position> position { get; set; }
}

public class position
{
    public float cost_basis { get; set; }
    public DateTime date_acquired { get; set; }
    public int id { get; set; }
    public decimal quantity { get; set; }
    public string symbol { get; set; }
}

And then decode them like this:

var responsebody = "{\"positions\":{\"position\":[{\"cost\":102.20000,\"date_acquired\":\"2013-11-18T19:54:13.730Z\",\"id\":192,\"quantity\":2.00000,\"symbol\":\"C\"},{\"cost\":121.50990,\"date_acquired\":\"2013-11-20T17:43:41.737Z\",\"id\":199,\"quantity\":1.00000,\"symbol\":\"TSLA\"}]}}";
positionsobj position = JsonConvert.DeserializeObject<positionsobj>(responsebody);

foreach (position item in position.positions.position)
{
     Console.WriteLine("Test : {0}", item.id);
}

But the class also had an extra problem in that quantity was a decimal and not a int. And your Console.Write was missing a {0} argument.

Upvotes: 10

Related Questions