What is the best practice to use in order to validate(e.g make sure that all the json parameters/ class properties are corectly written , sime of them to be of valid type like DateTime, int or in some cases to not allow to be null) a json file before deserialize it into a dto for example?
Thanks
Related
I have some JSON here. The problem is it doesn't match the classes data types anymore. My question is; is it possible to deserialize JSON Dynamically? i.e. if I have entirely different JSON's can I deserialize them into two entirely different classes without first knowing what class I want to deserialize each into.
You can deserialize dynamic object with using newtonsoft
like bellowing code piece.
dynamic dynamicObj = JsonConvert.DeserializeObject(jsonStr);
string name = dynamicObj.data.code;
But in my personal preference is using strong type. I think its more convenience.
you can use quictype for generating c# classes from JSON object
quicktype generates strongly-typed models and serializers from JSON,
JSON Schema, and GraphQL queries, making it a breeze to work with JSON
type-safely in any programming language.
Hope the answer helps to you.
I am working on a project that communicates a lot of data with a server. This data is in a json format. We end up creating a lot of dummy objects to parse the json data. This leads to having a lot of classes that just contain class members. Is there a better way of doing things?
thanks
Assuming that you are using NewtonSoft's JSON parser or something similar, you have a couple of choices here. The usual use case here is to deserialize to a named type, thus:
var parsedMessage = JsonConvert.DeserializeObject<Message>(content.AsString());
If you have many types for each differnet JSON message type you wish to receive and wish to avoid to, you can do the following:
var parsedMessage = JsonConvert.DeserializeObject<dynamic>(content.AsString());
This will give you a dynamic object that you can inspect and should also work given other Json libraries. Alternatively, NetwtonSoft also provides the following method:
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject);
This will allow you to deserialize to an anonymously typed object rather than a dynamic object.
I have some JSON data :-
{
"mail":"mitch#domain.com",
"givenName":"User",
"sn":"Name",
"uid":"mitch",
"gecos":"User Name"
}
What I'm trying to do is de-serialize this into a List<KeyValuePair<string,string>>
I would normally do a dictionary, however some key's may be duplicated - this is the representation that is automatically generated by .NET when I pass a List<KeyValuePair<string,string>> object into the System.Web.Script.Serialization.JavaScriptSerializer class.
When I just plug the serialized object into the System.Web.Script.Serialization.JavaScriptDeserializer I get a empty response back.
From what I can see it should not be possible using the JavaScriptSerializer. The only way for customizing its behavior is by means of a JavaScriptConverter class, that will allow you to customize the serialization/deserialization process. Unfortunately both methods will pass an IDictionary for the properties, therefore the duplicated names are already merged. You might want to look into either a different format for your JSON or a different serialization library such as JSON.net which is way more customizable.
A Chat Room sample program created with NodeJs.
Node.js server will response 3 different format of Json.
I have created a Winform program to accept Json from Websocket.
I use Json.NET JsonMessage jsonResponse =
JsonConvert.DeserializeObject(e.Message.ToString());
to deSerialize one format of Node.js
How to identify different format of Json when serialized?
three type of Json Format
color : "{\"type\":\"color\",\"data\":\"blue\"}"
message : "{\"type\":\"message\",\"action\":\"Change Color\"}"
history : "{\"type\":\"history\",\"data\":[{\"time\":1384825833181,\"text\":\"this is test\",\"author\":\"Tom\",\"color\":\"green\"},{\"time\":1384842730192,\"text\":\"WinForm Send\",\"author\":\"WinForm Say Hello!\",\"color\":\"orange\"},{\"time\":1384842808185,\"text\":\"WinForm Send Again!!!\",\"author\":\"WinForm Say Hello!\",\"color\":\"red\"},{\"time\":1384843229766,\"text\":\"I am fine\",\"author\":\"who are you\",\"color\":\"red\"}]}"
All of the 3 Json formats can create 3 different Class with JsonProperty to map them.
I can verify string with the first few characters.
Are there any other solutions?
I found the following solution could help.
Use JsonCreationConverter . How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?
Use JavaScriptSerializer with dynamic type
Parse json string using JSON.NET
var jss = new JavaScriptSerializer();
dynamic data = jss.Deserialize<dynamic>(e.Message.ToString());
Use JObject.Parse with dynamic type
Deserialize json object into dynamic object using Json.net
Serialized data is as string so, its just a string. As you have also told that you want to identify JSON format. So, better is first convert to JSON & then identify the JSON data type and based on the type call the process or method to process that data.
I need to serialize the strings from a resource file (.resx) into a JSON object. The resource file's keys are in flux and thus I cannot just create a C# object that accepts the appropriate values. It needs to be a dynamic solution. I am able to loop through the key-value pairs for the file, but I need an easy way to serialize them to JSON.
I know I could do:
Object thing = new {stringOne = StringResource.stringOne; ...}
But, I'd rather have something like:
Object generic = {}
foreach (DictionaryEntry entry in StringResource) {
generic.(entry.Key) = entry.Value
}
Or should I just create a custom JSON serializer that constructs the object piecemeal (i.e. foreach loop that appends part of the JSON string with each cycle)?
EDIT
I ended up writing a quick JSON serializer that constructs the string one field at a time. I didn't want to include a whole JSON library as this is the only use of JSON objects (for now at least). Ultimately, what I wanted is probably impractical and doesn't exist as it's function is better served by other data structures. Thanks for all the answers though!
If you're using C# 4.0, you should look at the magical System.Dynamic.ExpandoObject. It's an object that allows you to dynamically add and remove properties at runtime, using the new DLR in .NET 4.0. Here is a good example use for the ExpandoObject.
Once you have your fully populated ExpandoObject, you can probably easily serialize that with any of the JSON libraries mentioned by the other excellent answers.
This sounds like an accident waiting to happen (i.e. creating output prior to cementing the structure), but it happens.
The custom JSON serializer is a compelling option, as it allows you to easily move from your dictionary into a JSON format. I would look at open source libraries (JSON.NET, etc) to see if you can reduce the development time.
I also think setting up in a slightly more structured format, like XML, is a decent choice. It is quite easy to serialize from XML to JSON using existing libraries, so you avoid heavy customization/
The bigger question is what purposes will the data ultimately serve. If you solve this problem using either of these methods, are you creating bigger problems in the future.
Probably I would use JSON.NET and the ability to create JSON from XML.
Then, you could create an XML in-memory and let JSON.NET convert it to JSON for you. Maybe if you dig deeper into the API, there are other options, too.
Newtonsoft is a library that has all kinds of nifty JSON tools...among them, on-the-fly one-line serializer and deserializers...check it out, it's my favorite JSON library out there
http://james.newtonking.com/pages/json-net.aspx
If I remember correctly, it has a class that will convert JSON to a .NET object without having to create the .NET object first. Think it is in the Json.Convert class
The way I do it is:
var serialiser = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serialiser.Serialize(data);
context.Response.Write(json);