I've got a Mass Transit message interface like this:
public interface IPerson
{
ICollection<PersonalName> Names { get; }
}
public class PersonalName
{
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string SecondName { get; set; }
public string Use { get; set; }
}
And this works for serializing and deserializing the message using the JsonMessageSerializer. I can also serialize the message using the XmlMessageSerializer, and the result looks a bit like this:
<person>
<names>
<familyName>Simpson</familyName>
<givenName>Homer</givenName>
<secondName>Jay</secondName>
<use>Official</use>
</names>
<names>
<givenName>Homie</givenName>
<use>Nickname</use>
</names>
</person>
And I can deserialize just it if the collection is empty or if it has more than one element. However, if the collection contains exactly one element, when I go to deserialize it, I get this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.ICollection`1[MyNs.PersonalName]' 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 change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'person.names.familyName'.
I can fix this by using an array or List<T>, but I'd really like to avoid doing that. Is there a way to get Mass Transit's XmlMessageSerializer to deserialize ICollection<T> types? Since Mass Transit uses Json.NET for serialization under the hood (even for XML), I'm hoping there's some way of annotating the type so that it can accept an ICollection<T>.
Instead of trying to deserialize:
{"FamilyName":"Smith","GivenName":"John"}
you have to pass in an array to deserialize:
[{"FamilyName":"Smith","GivenName":"John"}]
Related
TL;DR
How do I convert json data that looks like this into a C# object using Newtonsoft.json and JsonConvert.DeserializeObject?
{"start":true,"result":{"label":"Setup Account","item":"name"}}
{"start":false,"result":{"label":"Change Account","item":"address"}}
{"start":false,"result":{"label":"Close Account","item":"account"}}
I am trying to deserialize some json exported from Splunk. The data does not look like an array, but rather a list of json objects between {}. Here are the first three objects of 600+ so you can see the format. The first one is actually the Splunk output. I shortened the "Search" in the next two.
{"preview":false,"result":{"label":"Internal Admin Nav","search":"<view isVisible=\"false\" >\n <label>Internal Admin Nav<\/label>\n <module name=\"Message\" layoutPanel=\"messaging\">\n <param name=\"filter\">*<\/param>\n <param name=\"clearOnJobDispatch\">False<\/param>\n <param name=\"maxSize\">1<\/param>\n <\/module>\n <module name=\"AccountBar\" layoutPanel=\"appHeader\">\n <param name=\"mode\">lite<\/param>\n <\/module>\n <module name=\"LiteBar\" layoutPanel=\"liteHeader\"><\/module>\n<\/view>"}}
{"preview":false,"result":{"label":"Setup Account","search":"AAAA"}}
{"preview":false,"result":{"label":"Contactless Dashboard","search":"BBBB"}}
If I try to create a class by pasting the first three lines into Visual Studio using Paste Special|Paste JSON as Classes, it complains that it is not Json data (Notepad++ seems to think it is though). If I just paste one of them {"preview":false,"result":{"label":"Contactless Dashboard","search":"BBBB"}} I get this object:
public class Rootobject
{
public bool preview { get; set; }
public Result result { get; set; }
}
public class Result
{
public string label { get; set; }
public string search { get; set; }
}
I have tied to deserialize in many ways.
Rootobject jsonObj = JsonConvert.DeserializeObject<Rootobject>(File.ReadAllText(fileName));
Error: Additional text encountered after finished reading JSON content:
List<Rootobject> jsonObj = JsonConvert.DeserializeObject<List<Rootobject>>(File.ReadAllText(fileName));
Error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ChecSourcetypes.Program+ObjClass]' 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 change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'preview', line 1, position 11.'
This is the most promising one and I tried to force it to deserialize by using a JsonObjectAttribute, but that just raised more problems.
I also added this class
public class RootRootobject
{
public List<Rootobject> objects { get; set; }
}
and then used this:
RootRootobject jsonObj = JsonConvert.DeserializeObject<RootRootobject>(File.ReadAllText(fileName));
I have messed with List<> and different objects without any success. I even converted the data to look like this:
[{"preview":false,"result":{"label":"Internal Admin Nav","search":"CCC"}},
{"preview":false,"result":{"label":"Setup Account","search":"AAAA"}},
{"preview":false,"result":{"label":"Contactless Dashboard","search":"BBBB"}}]
How do I read this json into an object? I would not want to change the Splunk output, but I could. I also would like to do it using JsonConvert.DeserializeObject. I recall doing this with Splunk data a few years ago using List<>, but do not remember how.
Thanks.
you have to fix your json to this (actually your last case)
[{"preview":false,"result":{"label":"Internal Admin Nav","search":"CCC"}},
{"preview":false,"result":{"label":"Setup Account","search":"AAAA"}},
{"preview":false,"result":{"label":"Contactless Dashboard","search":"BBBB"}}]
use your first classes
public class Rootobject
{
public bool preview { get; set; }
public Result result { get; set; }
}
and this code
List<RootRootobject> jsonObj = JsonConvert.DeserializeObject<List<RootRootobject>>(yourFixedJson);
I have a class which contains the ocject DateTime.
public class Refuel
{
public DateTime DateTime { get; set; }
public string Litre { get; set; }
}
When deserializing my text file I get an error.
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[OD_TankApp.Models.Refueling]' 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 change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'DateTime', line 1, position 12.
I tried already with Json settings but it didnt helped.
JsonSerializerSettings settings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat};
this is the json string:
"{\"DateTime\":\"2019-02-28T16:21:06.36845+01:00\",\"Litre\":\"23\"}}"
You are trying to deserialize a json string which represents a single object into a list/array of objects which will not work. Either deserialize it into a single object like this:
var obj = JsonConvert.DeserializeObject<Refuel>(json);
Or change your json string to contain a list of objects:
"[{\"DateTime\":\"2019-02-28T16:21:06.36845+01:00\",\"Litre\":\"23\"}]"
Now you can deserialize it like that:
var objArray = JsonConvert.DeserializeObject<Refuel[]>(json);
If you want to deserialize an array, you'll need to secify that ([])
JsonConvert.DeserializeObject<Refuel[]>(json);
I want to deserialize json into collection of C# objects but getting following error:
{"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1 because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'organizations', line 1, position 17."}
Code:
var jSon = "{\"Houses\":[{\"id\":\"123\",\"doorNumber\":22},
{\"id\":\"456\",\"deniNumber\":99}
]}";
var temp = JsonConvert.DeserializeObject<List<House>>(jSon);
}
public class House
{
public int Id { get; set; }
public int DoorNumber { get; set; }
}
The JSON you've shown is an Object with a Property called Houses that contains your array. Note how the outer Json is surrounded by { } and not [ ] which is why you're seeing that error. You'll need to select only the value of that property if you want to deserialize to a list of House. You can do that using JObject and then selecting the Houses property specifically.
var jobj = JObject.Parse(jSon);
var houses = JsonConvert.DeserializeObject<List<House>>(jobj["Houses"].ToString());
Alternatively you could do:
var houses = JObject.Parse(jSon)["Houses"].ToObject<List<House>>();
If you want to be able to map it in one step without using JObject you'd have to have another class that wraps your House list and maps directly to the JSON you've shown.
public class HouseList
{
public List<House> Houses {get; set;}
}
Given this object you'd be able to do
var houses = JsonConvert.DeserializeObject<HouseList>(jSon).Houses;
This might be a basic question but I am stuck while converting a JSON Response to a List.
I am getting the JSON Response as,
{"data":[{"ID":"1","Name":"ABC"},{"ID":"2","Name":"DEF"}]}
Have defined a Class,
class Details
{
public List<Company> data { get; set; }
}
class Company
{
public string ID { get; set; }
public string Name { get; set; }
}
Have tried this for converting,
List<Details> obj=List<Details>)JsonConvert.DeserializeObject
(responseString, typeof(List<Details>));
But this returns an error, saying
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Client.Details]' 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 change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Kindly help!
You don't have a List<Detail> defined in your JSON. Your JSON defines one Detail record, which itself has a list of companies.
Just deserialize using Details as the type, not List<Details> (or, if possible, make the JSON wrap the single detail record into a one item array).
You need to Deserialize like this:
var Jsonobject = JsonConvert.DeserializeObject<Details>(json);
using classes generated by json2csharp.com:
var Jsonobject = JsonConvert.DeserializeObject<RootObject>(json);
and your classes should be :
public class Datum
{
public string ID { get; set; }
public string Name { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
you can always use json2csharp.com to generate right classes for the json.
You can use JavaScriptDeserializer class
string json = #"{""data"":[{""ID"":""1"",""Name"":""ABC""},{""ID"":""2"",""Name"":""DEF""}]}";
Details details = new JavaScriptSerializer().Deserialize<Details>(json);
EDIT: yes, there's nothing wrong with OP's approach, and Servy's answer is correct. You should deserialize not as the List of objects but as the type that contains that List
I have a C# Application in which I am using Json.Net from Nuget.
I get a json from my server which I need to convert into a C# object and with a few modifications I will send it back to the server as json.
Here's my model in C# (which I got after converting the server xsd)
public class Tags
{
public List<Tag> tagData { get; set; }
}
public class Tag
{
public string name {get; set;}
}
Here's my JSON string that is obtained from the server and an attempt at conversion to my model
//Json string obtained from server (hardcoded here for simplicity)
string json = "{tagData: {tags : [ { name : \"John\"}, { name : \"Sherlock\"}]}}";
//An attempt at conversion
var output = JsonConvert.DeserializeObject<Tags>(json);
This is the exception I get with the above code
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[jsonnetExample.Tag]' 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 change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'tagData.tags', line 1, position 17.
After understanding the above message I tried the following 2 things in the hope of fixing it.
A.I tried putting a JsonProperty to my first model.
[JsonProperty(PropertyName = "tags")]
This didn't throw the exception anymore but the output tagData was null.
B. I modified my model as follows
public class Tags
{
public WrapTag tagData { get; set; }
}
public class WrapTag
{
public List<Tag> tags { get; set; }
}
public class Tag
{
public string name {get; set;}
}
This didn't throw any exception and populated the objects as expected. But Now I lost the one to one mapping between xsd(classes from the server) to my client model classes. Is it possible to get this deserialization working without the creation of the WrapTag class?
I would be very glad if someone can point me in the right direction.
Thanks in advance.
Here's one option, using JObject.Parse:
string json = "{tagData: {tags : [ { name : \"John\"}, { name : \"Sherlock\"}]}}";
List<Tag> tagList = JObject.Parse(json)["tagData"]["tags"].ToObject<List<Tag>>();
// or:
// List<Tag> tagList = JObject.Parse(json).SelectToken("tagData.tags")
// .ToObject<List<Tag>>();
Tags tags = new Tags { tagData = tagList };