Reputation: 1
I´m trying to use Newtonsoft to deserialize a Json string, but I´m getting this error :
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ShopFacilBradescoTeste.Erros' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'erros.$values', line 1, position 45.
This is my Json Data :
string json = @"{""$id"": ""1"",""erros"": {""$id"": ""2"",""$values"": []},""isValid"": true,""message"": null,""retornoConsulta"": {""$id"": ""3"",""$values"": [{""$id"": ""4"",""tipoLogradouro"": ""Rua"",""logradouro"": ""Abel Tavares"",""bairro"": ""Jardim Belém"",""localidade"": ""São Paulo"",""uf"": ""SP"",""cep"": ""03810110""}]}}";
Retorno result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
And these are my classes :
public class Retorno
{
public string id { get; set; }
public Erros erros { get; set; }
public bool isValid { get; set; }
public object message { get; set; }
public Retornoconsulta retornoConsulta { get; set; }
}
public class Erros
{
public string id { get; set; }
public object[] values { get; set; }
}
public class Retornoconsulta
{
public string id { get; set; }
public Values[] values { get; set; }
}
public class Values
{
public string id { get; set; }
public string tipoLogradouro { get; set; }
public string logradouro { get; set; }
public string bairro { get; set; }
public string localidade { get; set; }
public string uf { get; set; }
public string cep { get; set; }
}
Any ideas ?
Thanks in advance.
Upvotes: 0
Views: 836
Reputation: 3500
Did you try like this
string json = @"[ {""$id"": ""1"",""erros"": {""$id"": ""2"",""$values"": []},""isValid"": true,""message"": null,""retornoConsulta"": {""$id"": ""3"",""$values"": [{""$id"": ""4"",""tipoLogradouro"": ""Rua"",""logradouro"": ""Abel Tavares"",""bairro"": ""Jardim Belém"",""localidade"": ""São Paulo"",""uf"": ""SP"",""cep"": ""03810110""}]} ] }";
You need to have like this
Your data must be between [ and ] for JSON array
Upvotes: 0
Reputation: 962
Your JSON doesn't look like a JSON. But that's ok, there are helper classes that can massage those kinks out.
This should do it:
parsedJson = System.Web.Helpers.Json.Encode(json);
Retorno result = Newtonsoft.Json.JsonConvert.DeserializeObject(parsedJson);
I just tested it on my IDE, seem to be fine.
Upvotes: 0