Hi I am getting a response from server which is something like this
{"total":110,"responses":{"13":26,"14":24,"15":40,"16":20}}
I am not able to deserialize it using DataContractJSONSerializer. I have tried various combination for it but no results.
I am using following class for de-serializing:
public class PollResponseRoot
{
public int total { get; set; }
public Dictionary<int, int> Responses;
}
but I always get the Response value null. Please let me know where I am going wrong.
Dictionaries are not supported by DataContractJsonSerializer, you could try your luck with Json.Net instead.
Also available on NuGet: http://nuget.org/List/Packages/Newtonsoft.Json
See my explanation on a similar question why it's not possible to decode such lists using DataContractJsonSerializer. Use Json.NET instead.
Related
I am trying to get around that C# prefers to have classes generated (I know they are easy to generate, but currently my format and parameters are changing a lot due to development in both client and server end).
Example of what I most often find when I try to find out to deserialize is that you first have to know the exact structure - then build a class - and then you can refer to it later on (it's fine, but it's just not what I would like to do):
Json format 1:
[{"FirstName":"Bob","LastName":"Johnson"},{"FirstName":"Dan","LastName":"Rather"}]
public class People
{
public string FirstName { get; set; }
public string LastName { get; set;}
}
public List<People> peopleList;
. . . // (same as first example)
//Change the deserialize code to type <List<Class>>
peopleList = deserial.Deserialize<List<People>>(response);
That of course is easy as long as the reply doesn't change format, if for example the reply changes to a nested field :
Json format 2:
[{"FirstName":"Bob","LastName":"Johnson"},{"data":{"nestedfield1"
:"ewr"} }]
I would of course have to change the class to represent that, but at the moment we are moving back and forth in formats and I would somehow like if there was a way where I could try to access json elements directly in the string?
For example, like I can do in Python:
mystring1 = reply ["firstName"] mystring2 = reply ["data"]["nestedfield1"]
Is there any way to achieve this in C#? It would speed up development rapidly if there was a way of accessing it without first referencing the output in the code to then once again reference the class variable that was created when referencing it.
And note it's for rapid development, not necessarily for the final implementation where I can see advantages by doing the class approach.
Another way of asking was maybe can it serialize taking any format (as long as its JSON) and dynamically build up a struct where I can access it with named keys and not as class variables?
to deserialize json without using classes you can use using Newtonsoft.Json
here's the code:
using System;
using Newtonsoft.Json;
using System.Text;
public class Program
{
public static void Main()
{
var myJSONString = "[{\"FirstName\":\"Bob\",\"LastName\":\"Johnson\"},{\"FirstName\":\"Dan\",\"LastName\":\"Rather\"}]";
dynamic obj = JsonConvert.DeserializeObject<dynamic>(myJSONString);
Console.WriteLine(obj[0].FirstName);
}
}
The obj will perform the same way you use when generating classes,
it can take any json string and deserialize into dynamic object regardless of structure of the json. Keep in mind that you won't get VS intellisense support.
UPDATE
Here's fiddle:
https://dotnetfiddle.net/xeLDpK
I'm forced to use GET requests to pass complex objects to my application.
How can I deserialize a querystring like this:
?people[andy]=12&people[bob]=43&people[charlie]=53&items=89&items=123&x=zulu
into a custom object like this?
public class myClass {
public Dictionary<string, int> people { get; set; }
public int[] items { get; set; }
public string x { get; set; }
}
Is there a better (more sophisticated) way to do this besides splitting it by & and looping through the results to manually set each value?
Any pointers / guidance would be greatly appreciated.
If you have control over the sending side of the application, I strongly suggest you use a different encoding method to make parsing easier. I would just JSON encode the entire object, and then URIencode the JSON if it must be in the query_string.
There are often fairly small (on the order of 2K characters) limits to the size of URIs including the query_string. If you are forced to use HTTP, depending on your use case and whether you have control over this, POST may be preferable.
See this question for some methods of deserializing JSON:
C# deserialize dynamic JSON
Parsing Google Plus JSON objects
Using C# and Newtonsoft.Json library how one can parse following json code?
[["tsg.lac",
[[["3a4a7e8e0b3d5d66"],["Friends",null,"Your real friends, the ones you feel comfortable sharing private details with.",null,null,null,null,null,null,2,2,null,"00000000",1,1,1]]
,[["5947b6d78a8231f3"],["Family",null,"Your close and extended family, with as many or as few in-laws as you want.",null,null,null,null,null,null,2,2,null,"00000001",2,1,1]]
,[["22d0e3ec8c38fa24"],["Acquaintances",null,"A good place to stick people you've met but aren't particularly close to.",null,null,null,null,null,null,2,2,null,"00000002",5,1,1]]
,[["1adf9b0b0987c2ad"],["Following",null,"People you don't know personally, but whose posts you find interesting.",null,null,null,null,null,null,2,2,null,"00000003",6,1,1]]
,[["15"],["Blocked",null,null,null,null,null,null,null,null,2,1,null,"z9",null,1,1]]]
,[]
]
]
Basically how do you parse Json if you do not know the original structure?
Is it possible to parse it into generic key/value collection?
You can parse it like
JArray jobj = (JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(jStr);
foreach (var x in jobj[0][1])
{
Console.WriteLine(x[0][0] + " " + x[1][2]);
}
and the output will be
3a4a7e8e0b3d5d66 Your real friends, the ones you feel comfortable sharing private details with.
5947b6d78a8231f3 Your close and extended family, with as many or as few in-laws as you want.
22d0e3ec8c38fa24 A good place to stick people you've met but aren't particularly close to.
1adf9b0b0987c2ad People you don't know personally, but whose posts you find interesting.
PS: JsonView is a very good tool to help you
I think the answer depends on what you want to do with the data. If you are looking to extract specific pieces of information, I would build a class that contains the elements that you are looking to use and has placeholders for the rest, then deserialize into that class.
You can verify that the class is constructed correctly by first serializing a sample class and verifying that it produces the same output as what you are trying to parse.
You could use
JsonConvert.DeserializeObject<ElementType>("your json string here");
where the ElementType must be defined for your json data, could be something like:
[Serializable]
public class ElementType
{
public string ConstituentID { set; get; }
public string Email { set; get; }
}
(this one i pulled from somewhere and it does not correspond to you JSON structure)
Ie. it must capture your JSON structure.
im tyring to deserialize my object coming from client side having following format:
{'goalplans':
[{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0},
{"goalPlan":0,"accountId":11,"objectiveId":17,"activity":35,"acctOwner":0,"planDay":"1/30/2013","spend_budget":12,"sortBy":0,"activityFlag":0}
]}
thing is that im not able to deserialze it on my server side .
Please tell me how can i deserialize the Json object to a list object like
List . i tried many ways but not working.
serialize/deserialize objects to/from JSON exist Since .NET 3.5, try this
using System.Web.Script.Serialization;
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
See here for more details
Hope this helps
One possible third party component is JSON.NET. Personally I have made very good experience with that library ( it is available using nuget for example )
I solved the problem by myself. Simply adding [Serializable] to my class
and changed method to take argument of class type ...
e.g.
//My class
[Serializable]
public class GoalPlanList{}
//method
public static int GoalplanAddUPD(List<GoalPlanList> goalplans)
{
foreach (GoalPlanList goals in goalplans)
{}
}
I'm writing an application that posts and gets JSON to/from a backend in Visual C# 4.0.
Obviously, the easiest way to serialize/deserialize the JSON is System.Web.Script.Serialization.JavaScriptSerializer, but I'm having a weird error where it's throwing a ArgumentNullException, claiming that type is null.
When the following JSON is deserialized, it works fine:
{"results":[
{"Name":"Western Bulldogs",
"updatedAt":"2011-08-22T09:09:09.673Z",
"Nickname":"Bulldogs",
"RemoteId":44,
"Abbreviation":"WB",
"createdAt":"2011-08-22T09:09:09.673Z",
"objectId":"2iSK8FDTA6"}
]}
However, when deserializing the second one (with the nested dictionary), it fails with the type is null error.
{"results":[
{"EndDate":{"iso":"2011-09-06T00:00:00.000Z","__type":"Date"},
"Name":"Round 24",
"updatedAt":"2011-08-22T08:33:54.119Z",
"RemoteId":800,"createdAt":"2011-08-22T08:33:54.119Z",
"Season":{"className":"Season","__type":"Pointer","objectId":"WnsdqIlrd6"},
"Order":24,
"StartDate":{"iso":"2011-08-30T00:00:00.000Z","__type":"Date"},
"objectId":"bLdBfhagi9"}
]}
For reference, I'm deserializing with the following method for both queries:
JavaScriptSerializer jsSerialise = new JavaScriptSerializer();
ObjectIdContainerList contList = jsSerialise.Deserialize<ObjectIdContainerList>(responseString);
Where ObjectIdContainerList is as follows (note - it does not implement all the properties of the original JSON object because I am only interested in getting the objectId property):
[Serializable]
public class ObjectIdContainerList
{
public ObjectIdContainer[] results { get; set; }
}
[Serializable]
public class ObjectIdContainer
{
public String objectId { get; set; }
}
The first query deserialises without issue with exactly the same code and objects.
Any suggestions? Would I be best off just going to JSON.NET?
I don't understand what's the purpose of ObjectIdContainerList when you should be able to simply do this:
jsSerialise.Deserialize<List<ObjectIdContainer>>(responseString)
and get a List of ObjectIdContainer
I would also make sure that ObjectIdContainer has a property called "__type" that holds a string. I mention it because that's a weird name for a class property in C#.
EDIT: I just saw that you posted the rest of your code...
Are you saying that you expect to be able to deserialize the response string into an array of ObjectIdContainer where ObjectIdContainer only has a property called objectId? I would be very impressed if you can manage to make that work.
I remember Reflector once showed me that the implementation of the JavascriptSerializer basically uses reflection to serialize/deserialize objects; therefore, you need a corresponding class with the same property names as the ones defined in your JSON object or else it will fail.
I feel kind of bad for answering my own question, but I ended up solving the problem by using Json.Net to deserialise the object with almost exactly the same code and it worked.
I'm not inclined to say that this is a bug in the .Net framework, but it kind of feels that way.
Thanks to those who helped!