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)
{}
}
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
This may be too much trouble, but I have an object I'm trying to deserialize that looks like this:
{
"Status": { ... a status object ... }
"Data" : {... could be any one of 10 other data classes I have ... }
}
I want to deserialize this object into a response class that looks like this:
public class Response
{
public Status Status;
public Stream Data;
}
Then later deserialize the Data attribute into another class. However, if I make the type of the data attribute a Stream, I get a Security Exception when I try to deserialize. Likewise, if I make it a string, the deserialize just calls the toString() method on the data object (after deserializing it) and puts that as the attribute, which isn't helpful.
Is there any way to accomplish something like this? I'm trying to avoid having 10 different classes that all look a lot like Response but just have a different type for the Data attribute. If there's a way that I can dynamically set the type of the Data attribute that might also solve the situation.
Thanks for any help!
I always use Newtonsoft.Json.dll to solve this problem.
I have a JSON String returned by my SOAP web service in .NET. It is as follows:
{
"checkrecord":
[
{
"rollno":"abc2",
"percentage":40,
"attended":12,
"missed":34
}
],
"Table1":[]
}
Now I want to parse this string to a JSON Object. I also read this where they have used this line of code:
JObject jsonObj = JObject.Parse(json);
So can I do the same by replacing "json" with my string name. Also do I need to reference any other dll except the NewtonSoft.dll ?
BTW, Here is the full webservice code
use new JavaScriptSerializer().Deserialize<object>(jsonString)
You need System.Web.Extensions dll and import the following namespace.
Namespace: System.Web.Script.Serialization
for more info MSDN
I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.
As #Maloric mentioned in his answer to this question:
var jo = JObject.Parse(myJsonString);
To use JObject, you need the following in your class file
using Newtonsoft.Json.Linq;
Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.
It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.
And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D
There is a System.Json.dll you should add to your project References.
-Jesse
Since you mentioned that you are using Newtonsoft.dll you can convert a JSON string to an object by using its facilities:
MyClass myClass = JsonConvert.DeserializeObject<MyClass>(your_json_string);
[Serializable]
public class MyClass
{
public string myVar {get; set;}
etc.
}
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.
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!