Deserialize json Object using newtonsoft json - c#

I have a json like
{"NewMessage":[{"Id":-1,"Message":"Test","MessageName":"test1"}],"OldMessage":[]}
and I need to deserialize this json in to my class object.
My Class
public class NewMessage{
public int Id{get;set;}
public string Message{get;set;}
public string MessageName{get;set;}
}
public class OldMessage{
public int Id{get;set;}
public string Message{get;set;}
public string MessageName{get;set;}
}
how can we achive this by using newtonsoft.json. can anyone help. thanks in advance

Your JSON actually contain an object which have properties of your defined classes - given the code posted, you don't have a class to deserialize into.
The first thing you can do is obvious - create a third class - MessagePair - which declares two properties - NewMessage[] and OldMessage[]. Then you can deserialize the JSON string like this:
var theMessages = JsonConvert.DeserializeObject<MessagePair>(jsonText);
If you don't like to create separate class, you can then deserialize into anonymous object like this:
var theMessages = new {
NewMessage[] NewMessages = null,
OldMessage[] OldMessages = null
};
theMessages = JsonConvert.DeserializeAnonymousType(jsonText, theMessages);

Related

Serialize and deserialize Json property to two different values

I have a source JSON object that I get from a server that looks like this:
{
"Property A": .098
}
I have a C# class that I deserialize the JSON into using the following:
public class foo {
[JsonProperty("Property A")]
public decimal PropertyA{ get; set;}
}
var ret = JsonConvert.DeserializeObject<foo>(File.ReadAllText(someJsonString);
This allows me to read in a JSON file and convert it to a C# object. But now I would like to write this object out to JSON but change the format to be this:
{
"property_a":.098
}
I currently have another class that is identical and the only difference is that I change the JsonProperty field to the new desired name:
public class foo {
[JsonProperty("property_a")]
public decimal PropertyA{ get; set; }
}
Is there a way using Newtonsoft to have a JsonProperty read as a particular value but write as a different?

Creating a custom JSON tokenizer

I am trying to parse JSON into a token object. Right now Im using JSON.Net to generate a static class, and parsing it using Json2csharp, but I would like to make each array element its own Token object and I'm not quite sure how to do that. Do I need to implement my own JSON parser? I can modify the JSON object as needed.
My JSON Deserializer: JSONopMap jo = JsonConvert.DeserializeObject<JSONopMap>(myjson2);
public class JSONopMap
{
List<List<string>>addr {get;set;}
}
JSON
{
'addr':[['~address'],['removeall','.'],['append',' ','~age']]
}
My end goal is to create a MyToken class like this:
public class MyToken
{
public enum tokenType {get;set;}
public List<string> parts {get;set;}
}
public class TokenParent{
public string ResultName{get;set;}
public List<MyToken> mytokens{get;set;}
}
public enum tokenType{Map,Append,Removeall,Lower}
So I would have three MyToken objects like this:
new MyToken{
tokenType=Map,
parts=new List<string>(){"~address"}
}
new MyToken{
tokenType=Removeall,
parts=new List<string>(){"."}
}
new MyToken{
tokenType=Append,
parts=new List<string>(){" ","~age"}
}
and a parent which contained them all:
new TokenParent{
ResultName="addr",
mytokens = (the tokens created above)
}

Deserialize string by class name

Let's say I have a Value that is deserialized from a class.
public class MyValue
{
public string MyPropertyA { get; set; }
public string MyPropertyB { get; set; }
public string DeserializationClass { get; } = typeof(MyValue).Name;
}
I serialize this using JsonConvert class. MyValue class has a property DeserializationClass that should be used as info from which class the string was serialized from. In other words, when I deserialize the string into an object, this property serves as info which class should be used to deserialize the string. However, I am kinda stuck here as I am not sure how to get back the class from the string. Can anybody help me here?
public class Program
{
void Main()
{
var serialized = Serialize();
var obj = Deserialize(serialized);
}
string Serialize()
{
var objValue = new MyValue { MyPropertyA="Something", MyPropertyB="SomethingElse" };
return JsonConvert.SerializeObject<MyClass>(value);
}
object Deserialize(string serialized)
{
//How to deserialize based on 'DeserializationClass' property in serialized string?
return = JsonConvert.Deserialize<???>(serialized);
}
}
EDIT: Modified example to make it more clear what I need as I don't have access to objValue when I need to deserialize the string.
probably you might need to use JsonSerializerSettings.
What you might need to do is
JsonSerializerSettings setting = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
};
and then while serializing use this setting.
var serialized = JsonConvert.SerializeObject(objValue,setting);
this will give you Json like this
{"$type":"WPFDatagrid.MyValue, WPFDatagrid","MyPropertyA":"Something","MyPropertyB":"SomethingElse","DeserializationClass":"MyValue"}
from this you can find the name of the class used it to actually get your type.
Hope this helps !!
There is an overload
If your Type is in form of a Namespace, you can obtain the type from a string representation:
Type objValueType = Type.GetType("Namespace.MyValue, MyAssembly");
object deserialized = JsonConvert.Deserialize(objValueType, serialized);

Converting JSON to list of dictionaries

I'm working on a Unity (C#) project and trying to convert JSON data from an API to a list of dictionaries. I'm trying to use Unity's JSONSerialization, but I'm not sure what to do.
In the documentation, it says the following, and I was wondering if anyone could guide me to how I can convert the JSON? Sorry for the easy question as I'm new to C# and in the other languages I use like Javascript/Python, this is quite easily done.
Passing other types directly to the API, for example primitive types
or arrays, is not currently supported. For now you will need to wrap
such types in a class or struct of some sort.
https://docs.unity3d.com/Manual/JSONSerialization.html
The JSON returned is as follows and is a list of dictionaries, and each dictionary has two keys (_id and firstName).
[{"_id":"xxx", "firstName":"Brayann"}, {"_id":"yyy", "firstName":"Peter"}]
Create object in which you will Deserialize the json. Call ToDictionary after that.
Full example: dotNetFiddle
public static void Main(string[] args)
{
string json = #"[{ ""_id"":""xxx"", ""firstName"":""Brayann""}, { ""_id"":""yyy"", ""firstName"":""Peter""}]";
var result = JsonConvert.DeserializeObject<List<RootListObject>>(json)
.ToDictionary(x=> x.id, y=> y.firstName);
}
public class RootListObject
{
[JsonProperty(PropertyName ="_id")]
public string id { get; set; }
public string firstName { get; set; }
}
As far as I know you can't deserialize as enumarable of dictionary but you can create a class for this purpose which is more reasonable:
public class SomeDataType
{
public string _id { get; set; }
public string firstName { get; set; }
}
Then you can deserialize as List<SomeDataType>.
Even if you really require the dictionary you can add a ToDictionary method to your class.

Parsing a JSON request in c# with a c# keyword

I'm trying to parse a JSON rpc 2.0 request. The standard is defined here.
I've defined my class as:
[DataContract]
public class JsonRpc2Request
{
public string method;
[DataMember(Name = "params")]
public object parameters;
public object id;
}
I then try and parse a request as follows:
JavaScriptSerializer ser = new JavaScriptSerializer();
var obj = ser.Deserialize<JsonRpc2Request>(Message.Trim());
obj.parameters is always null. I think this is because I can't define an object with the name params as per the JSON RPC spec. (My attempt is using the [DataMember(Name="params")] decoration.
How can I populate my parameters object when the JSON RPC spec calls for the name params which is a keyword in c#?
You can use the DataContractJsonSerializer:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(JsonRpc2Request));
MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(Message.Trim()));
var obj = ser.ReadObject(stream);
and you'll want to annotate method and id with the DataMember attribute as well.
I would use Json.Net to get the full control over serialization/deserialization process
string json = #"{""method"":""mymethod"",""params"":[1,2],""id"":3}";
var rpcReq = JsonConvert.DeserializeObject<JsonRpc2Request>(json);
public class JsonRpc2Request
{
[JsonProperty("method")]
public string Method;
[JsonProperty("params")]
public object[] Parameters;
[JsonProperty("id")]
public string Id;
}
Since after completing this step, you are going to have to deal with more complex cases like
#"{""method"":""mymethod"",""params"":[{""name"":""joe""}],""id"":3}";

Categories

Resources