I get a list with list in json And want to convert the json to matrixList Object but cant get it to work Im getting this error
System.Collections.Generic.Dictionary`2[System.String,System.Object]
here is my code
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
matrixList mxList = (matrixList)json_serializer.DeserializeObject("{ \"matrix\": "[[\"1\",\"email1#gmail.com\"],[\"2\",\"email2#gmail.com\"],[\"3\",\"email3#gmail.com\"],[\"4\",\"email4#gmail.com\"]]" }");
The values of the Json is just an example
public class matrixList
{
public List<List<string>> matrix { get; set; }
}
My question then why wont it work I have searched on the error and only found some with Json syntax error but Im not able to see any error.
Tahks for the help
Try adding a RootObject first.
public class RootObject
{
public RootObject(){}
public List<string> itemList{get;set;}
}
Then try deserializing to the RootObject type.
When deserializing Lists this works with Newtonsoft.JSON serializer.
serializer.DeserializeObject<RootObject>(jsonInput);
Related
I have a very big JSON Array in an external File (http://gta5multiplayer.de/Upload/VehicleData.json)
I'm using File.ReadAllText(path); to get the json which works perfectly.
I created a class and a Dictionary which shell hold the deserialized information. https://pastebin.com/EMi5zpnN and
public class VehicleTest
{
public Dictionary<int, VehicleInfo> Data { get; set; }
public VehicleTest()
{
}
}
The deserialization works fine for one object of the array but the whole
array cannot be deserialized with my dictionary.
Do you have any advice to deserialize the whole array?
The deserializing fails because you're missing the root element in your Json file.
Modify your Json file as follows:
{
"Data":{
....
}
}
And it should work.
This is my JSON string:
{"type":"motor","ids":["1","2","5","7","8","10"]}
And this is the object I want to generate from it:
public class ElementArray {
public ElementType type;
public String[] ids;
public ElementArray() {
}
}
How can I achieve that? I googled about Json.NET, but they only explain how to deserialize an array but not how to deserialize an object containing an array as a field (see my class above).
What I tried is
JavaScriptSerializer jss = new JavaScriptSerializer();
ElementArray elements = jss.Deserialize<ElementArray>(strJson);
but when I debug the code, the field ids contains null.
IMO simplest way to deal with json is using newtonsoft.json library
http://www.newtonsoft.com/json
And here is example how to deserialize object:
http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
I have the following raw JSON string:
[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]
I have tried the following without luck:
My custom object class:
public class MyObject
{
public string msg { get; set; }
public string id { get; set; }
public string chn { get; set; }
}
JSON string:
string str = "[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]";
1st attempt at deserilization using System.Web.Script.Serialization:
JavaScriptSerializer serializer = new JavaScriptSerializer();
MyObject obj1 = serializer.Deserialize<MyObject>(str);
2nd attempt at deserilization using Newtonsoft.Json:
MyObject obj2 = JsonConvert.DeserializeObject<MyObject>(str);
Both attempts fail. Any suggestions?
You have a JSON array of strings, not an object with property names.
So the best you can do here is to deserialize the array:
IEnumerable<string> strings =
JsonConvert.DeserializeObject<IEnumerable<string>>(str);
...then use the resulting sequence strings as you see fit.
With PubNub, you can just pass in the native String, Dictionary, or Array, and we'll JSON encode it for you on the publish side, and auto JSON decode for you on the subscriber side.
It's because your 'custom object' isn't equivalent to the json representation. The json you're deserializing is just a string[] in C# (you can also use List<string> or other IEums).
So in code you're looking for;
string[] theJson = JsonConvert.DeserializeObject<string[]>(str);
MyObject would be used for the following json;
{
"msg":"Hello World!",
"id":"94952923696694934",
"chn":"MyChannel"
}
I am using Newtonsoft.Json with version 4.0.8 and trying to use it with Web API.
So I wanted to deserialize JSON with
JsonConvert.DeserializeObject<AClass>(jsonString);
This works until I added a Dictionary as property to this class and wanted to deserialize it.
The json string is in the form of
{
"Date":null,
"AString":"message",
"Attributes":[
{"Key":"key1","Value":"value1"},
{"Key":"key2","Value":"value2"}
],
"Id":0,
"Description":"...
}
When deserializing exception of type JsonSerializationException occures with message: "Cannot deserialize JSON array into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'."
What am I doing wrong here?
UPDATE1:
When serializing with JSON.NET i get the following for the dictionary:
Attributes":{"key1":"value1","key2":"value2"}
Seems that WebApi deserializes the object in an other way than Json.Net would.
Server side I use following line for implicit deserializing:
return new HttpResponseMessage<AClass>(object);
UPDATE2:
As a workaround I came now to following line server side.
return new HttpResponseMessage<string>(JsonConvert.SerializeObject(license).Base64Encode());
I convert it with Json.Net server side and transfer it as base64 encoded string. So Json.Net can deserialize its own format.
But its still not that what I want, so are thery any further suggestions?
It should work if you declare Attributes as List<KeyValuePair<string, string>>
From this post, calling
JsonConvert.SerializeObject(yourObject, new KeyValuePairConverter());
gets your JSON in the format that the Web API is creating for you.
Ergo, one might assume that calling
JsonConvert.DeserializeObject<AClass>(jsonString, new KeyValuePairConverter());
will do the reverse and correctly handle the Web API's style.
I have no idea whether this overload even exists, though; give it a try and see what happens...
Dictionary<string, object> result = JsonConvert.DeserializeObject<Dictionary<string, object>>(strJsonResult);
If it's .NET 4, you can use DataContract attributes and the DataContractJsonSerializer Class to enforce the message format:
[DataContract]
public class Message
{
[DataMember]
public DateTime? Date { get; set; }
[DataMember]
public string AString { get; set; }
[DataMember]
public Dictionary<string, string> Attributes { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string Description { get; set; }
}
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Message));
Message message = null;
using (MemoryStream jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
// Deserialize
message = (Message)jsonSerializer.ReadObject(jsonStream);
// Go to the beginning and discard the current stream contents.
jsonStream.Seek(0, SeekOrigin.Begin);
jsonStream.SetLength(0);
// Serialize
jsonSerializer.WriteObject(jsonStream, message);
jsonString = Encoding.UTF8.GetString(jsonStream.ToArray());
}
Serializing this back out produces the following JSON:
{"AString":"message","Attributes":[{"Key":"key1","Value":"value1"},{"Key":"key2","Value":"value2"}],"Date":null,"Description":"...","Id":0}
here's my problem:
I'm trying to deserialize json that hasn't been done by me. The format of the json is as follows:
{"responseId":1200,
"availableHotels":[
{"processId":"HA-84665605","hotelCode":"UKKTLT","availabilityStatus":"InstantConfirmation",...},
{"processId":"HA-28600965","hotelCode":"UKKTLT","availabilityStatus":"InstantConfirmation",...},
{"processId":"HI-63991185","hotelCode":"UKJOVF","availabilityStatus":"InstantConfirmation",...}
],
"totalFound":9,
"searchId":"TP-84026455"}
And the following classes:
getAvailableHotelResponse w/properties:
hotelObj availableHotels
int totalFound
String responseId
String searchId
hotelObj w/properties:
hotel hotel
hotel w/properties:
processId
hotelCode
availabilityStatus
...
Therefore, what I know I can tell from looking at the json is that it contains information of a getAvailableHotelResponse object.
So, I tried the following using JsonConvert and JavaScriptSerializer:
JavaScriptSerializer ser = new JavaScriptSerializer();
getAvailableHotelResponse availableResponse = ser.Deserialize<getAvailableHotelResponse>(json);
// Exception: "Type 'com.hotelspro.api.getAvailableHotelResponse' is not supported for deserialization of an array"
List<getAvailableHotelResponse> items = ser.Deserialize<List<getAvailableHotelResponse>>(json);
// items.Count = 0
List<getAvailableHotelResponse> result = JsonConvert.DeserializeObject<List<getAvailableHotelResponse>>(json);
// Exception: "Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[com.hotelspro.api.getAvailableHotelResponse]'."
getAvailableHotelResponse result2 = JsonConvert.DeserializeObject<getAvailableHotelResponse>(json);
// Exception: Cannot deserialize JSON array into type 'com.hotelspro.api.hotelObj'.
What's the correct sentence in order to deserialize this object?
Thanks!
It's difficult to interpret the structure of your objects based on your description but I was able to deserialize your sample JSON using the following minimal code:
var result = JsonConvert.DeserializeObject<getAvailableHotelResponse>(json);
public class getAvailableHotelResponse
{
public int responseId;
public availableHotel[] availableHotels;
public int totalFound;
public string searchId;
}
public class availableHotel
{
public string processId;
public string hotelCode;
public string availabilityStatus;
}
Neither of the above listed Objects fully match the JSON schema... Are you sure whoever serialized the object to JSON used any of those classes you're trying to deserialize to? If not, just create a class that you deserialize the JSON to:
public class HotelSearchResponse
{
public int responseID {get;set;}
public hotel[] availableHotels {get;set;}
public int totalFound {get;set;}
public string searchId {get;set;}
}
If the hotel array doesn't work, try List<hotel> instead for availableHotels type.
P.S. The closest object to the JSON from the ones listed in your question is getAvailableHotelResponse but it declares availableHotels as single hotel instace, instead the JSON has an array of hotel objects returned.