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.
Related
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.
Similar to JSON.NET deserialize to object with Type parameter, I need to deserialise some JSON, which has been previously serialised:
Serialisation code:
...
Data = new ImplementationofICommandData{ Id = Id }
DataType = typeof(ImplementationofICommandData).AssemblyQualifiedName,
...
Deserialisation code:
...
(ICommandData)JsonConvert.DeserializeObject(dto.Data, Type.GetType(dto.DataType))
...
In this case, dto.DataType contains the AssemblyFullName.
Initially, the projects that contained the serialisation and deserialisation shared a project with DTOs in it, so the deserialisation was able to use the same AssemblyQualifiedName for the type.
Now, I have a new project that is serialising data to the database. I have a DTO in the original shared project that has the exact same structure as the DTO in the new project, but due to being in a different assembly, the AssemblyQualified name that gets serialised does not correspond to a type about which the deserialising code knows.
Ideally, I won't have to make the serialisation and deserialisation code share the same DTO project, so is it possible to get the type by something less than the AssemblyQualifiedName? Or is there a better approach?
As it stands, I've added a default namespace/assembly to search for a bare class name. This could be expanded to allow for a non-hack method of registration of a list of namespaces/assemblies in which to search for the DTO class, all wrapped up in some kind of resolver class.
I'm looking for a JSON parser and encoder for .NET that can parse JSON into its own data structure which I can then navigate, as opposed to directly deserializing it into a class. In Java, I use Jettison's JSONObject and JSONArray which is dead easy to use.
There are a number of reasons why I don't want to (de)serialize:
Serializers tend to add metadata to the JSON and require that metadata for deserialization (e.g. fastJSON and JSON.NET add type info).
I don't want the hassle of having to create a bunch of classes to handle all the different types of data. Also, I want to be able to ignore fields I'm not interested in rather than have to add properties to them.
Is there anything available or do I have to port a subset of Jettison?
The disadvantages of serialization that you point out aren't really there, at least in the case of JSON.NET:
JSON.NET doesn't add any metadata by default. You can tell it to add the metadata if you need it (for example, when one property can hold values of different types), but it's optional.
You replace the hassle of creating classes with the hassle of working with strings and casts and I think that's much worse. Also, you can ignore fields you're not interested in, just don't add them to your types.
But, if you really want to do that, you can. The equivalent types are JObject and JArray, so, if you want to deserialize some object, use:
JObject obj = JsonConvert.DeserializeObject<JObject>(json);
As another option, you don't have to specify the type you want at all, ant it will return either JObject or JArray:
object objectOrArray = JsonConvert.DeserializeObject(json);
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);