I'm looking for a way to do deserialization from Json to be version dependent using the data within the Json itself.
I'm targeting to use ServiceStack.Text.JsonDeserializer, but can switch to another library.
For example, I'd like to define a data in JSON for v1.0 to be:
{
version: "1.0"
condition: "A < B"
}
and then, a next version of the data (say 2.0) to be:
{
version: "2.0"
condition: ["A < B", "B = C", "B < 1"]
}
At the end, I want to be able to validate version of the data to know how to deserialize the JSON correctly.
UPDATE:
It looks like there is no any kind of implicit support for version-dependent JSON (de)serialization in known products.
The right solution seems to be to split the task by (de)serializing only version part and then use implicit (de)serializing for the correct type(s).
Gratitudes to everyone who shared knowledge and thoughts on the problem.
What you can do is either the following:
Create a base class for the data objects you want to deserialize that contains a version field and nothing else.
Make the data classes for your different versions be derived classes of this base class.
When you deserialize your data object, first, deserialize it as an instance of your base class - so now you have a POCO object that contains the version number. You can use this to decide which of your derived data classes you should use to deserialize your data (in the simplest case, you can do a switch/case and handle each version individually)
An example (using System.Web.Script.Serialization.JavaScriptSerializer):
class BaseClass
{
public int version { get; set; }
}
class FirstVersion: BaseClass
{
public string condition { get; set; }
}
class SecondVersion: BaseClass
{
public IEnumerable<string> condition { get; set; }
}
public void Deserialize (string jsonString)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
BaseClass myData = serializer.Deserialize<BaseClass>(jsonString);
switch (myData.version)
{
case 1:
FirstVersion firstVersion = serializer.Deserialize<FirstVersion>(jsonString);
// ...
break;
case 2:
SecondVersion secondVersion = serializer.Deserialize<SecondVersion>(jsonString);
// ...
break;
}
}
As you can see, this code deserializes the data twice - that may be a problem for you if you are working with large data structures. If you want to avoid that at all costs, you either have to give up static typing or modify the data model of your application.
And here is how it looks like with dynamic:
public void Deserialize (string jsonString)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic myData = serializer.Deserialize<object>(jsonString);
if (myData ["version"] == 1) {
...
}
}
There is also the option to write your own custom JavaScriptConverter. That is a lot more work, but I'm pretty sure you can achieve what you want and it will look nicer.
Another advice to consider is never to remove properties from your JSON structure. If you need to modify a property, keep the old one and add a new one instead - this way, old code can always read data from newer code. Of course, this can get out of hand pretty quickly if you modify your data structures a lot...
In Java, you could use Google's GSON library, as it has a built-in support for versioning. I haven't looked into it, but it is open source and if it's really important to you, I guess you can port the implementation to a different language.
I suggest that you use json.net is it allows you to add your custom type converts which can be used for versioning.
The problem is not serialization as it will always use the current schema. The problem is when the client uses a different type version that the server that receives the object.
What you need to do is to check the version programatically in your type converter and the convert the value by yourself (in this case convert the string to an array).
Documentation: http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
You might want to use the NewtonSoft.Json NuGET package.
This is kind of a standard within the .NET community. It is also often referred to as Json.NET
You can use it like this (example from official website):
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
If you are willing to switch to JSON.net, then there is a simpler way of doing it. You don't have to use a BaseClass containing version and you don't have to parse twice. The trick is to use JObject and then query JSON for the version:
JObject obj = JObject.Parse(json);
string version = obj.SelectToken("$.Version")?.ToString();
Then you can proceed as Sándor did with the bonus part that you can use JObject to get your dto instead of re-reading json:
ConditionsDto v1Dto = obj.ToObject<ConditionsDto>(readSerializer);
Putting it all together:
public static ConditionsBusinessObject Parse(string json)
{
JObject obj = JObject.Parse(json);
string version = obj.SelectToken("$.Version")?.ToString();
JsonSerializer readSerializer = JsonSerializer.CreateDefault(/*You might want to place your settings here*/);
switch (version)
{
case null: //let's assume that there are some old files out there with no version at all
//and that these are equivalent to the version 1
case "1":
ConditionsDto v1Dto = obj.ToObject<ConditionsDto>(readSerializer);
if (v1Dto == null) return null; //or throw
List<string> convertedConditions = new List<string> {v1Dto.Condition}; //See what I've done here?
return new ConditionsBusinessObject(convertedConditions);
case "2":
ConditionsDtoV2 v2Dto = obj.ToObject<ConditionsDtoV2>(readSerializer);
return v2Dto == null ? null //or throw
: new ConditionsBusinessObject(v2Dto.Condition);
default:
throw new Exception($"Unsupported version {version}");
}
}
For reference here are the classes that I have:
public class ConditionsDto
{
public string Version { get; set; }
public string Condition { get; set; }
}
public class ConditionsDtoV2
{
public string Version { get; set; }
public List<string> Condition { get; set; }
}
public class ConditionsBusinessObject
{
public ConditionsBusinessObject(List<string> conditions)
{
Conditions = conditions;
}
public List<string> Conditions { get; }
}
and a couple of tests to wrap it up:
[Test]
public void TestV1()
{
string v1 = #"{
Version: ""1"",
Condition: ""A < B""
}";
//JsonHandler is where I placed Parse()
ConditionsBusinessObject fromV1 = JsonHandler.Parse(v1);
Assert.AreEqual(1, fromV1.Conditions.Count);
Assert.AreEqual("A < B", fromV1.Conditions[0]);
}
[Test]
public void TestV2()
{
string v2 = #"{
Version: ""2"",
Condition: [""A < B"", ""B = C"", ""B < 1""]
}";
ConditionsBusinessObject fromV2 = JsonHandler.Parse(v2);
Assert.AreEqual(3, fromV2.Conditions.Count);
Assert.AreEqual("A < B", fromV2.Conditions[0]);
Assert.AreEqual("B = C", fromV2.Conditions[1]);
Assert.AreEqual("B < 1", fromV2.Conditions[2]);
}
In a normal real world application, the //See what I've done here? part is where you will have to do all your conversion chores. I didn't do anything smart there, I just wrapped the single condition to a list to make it compatible with the current business object. As you could guess though, this can explode as the application evolves. This answer in softwareengineering SE has more details in the theory behind versioned JSON data so you might want to have a look in order to know what to expect.
One final word about performance impact of reading to JObject and then converting to the dto is that I haven't done any measurements but I expect it to be better than parsing twice. If I find out that this is not true, I will update the answer accordingly.
Take a look at
System.Web.Script.Serialization.JavaScriptSerializer
Sample
var ser = new JavaScriptSerializer();
var result = (IReadOnlyDictionary<string, object>)ser.DeserializeObject(json);
if(result["version"] == "1.0")
{
// You expect a string for result["condition"]
}
else
{
// You expect an IEnumerable<string> for result["condition"]
}
Related
I am trying to create a json formatted string using c# in UWP without JSON.Net, but I am just not understanding how to get there. Let's say I wanted to create the following json dynamically:
[{"id":130},{"id":131},{"id":132},{"id":133},{"id":134}]
From everything I have read, it would seem that I need a class that defines the content of my json. For example:
class accountTypes
{
public int id { get; set; }
public string type { get; set; }
}
From there, it would seem that I only need to create a list of type "accountTypes" and then add each "id" to the list.
List<accountTypes> jsonList = new List<accountTypes>();
int numOfChildren = AccountTypesList.Children.Count;
for (int i = 0; i < numOfChildren; i++)
{
if (((CheckBox)AccountTypesList.Children[i]).IsChecked == true)
{
jsonList.Add(new accountTypes() { id = (int)(double)((CheckBox)AccountTypesList.Children[i]).Tag });
}
}
While I am 99% sure that the above code is very flawed, it does not crash on me, so that is a start at least. What I am struggling with now though is how I would serialize the list "jsonList". Everything I have read thus far either points to JSON.net or the JavaScriptSerializer Class, and not Windows.Data.Json. If I could see a simple example on how to serialize json using Windows.Data.Json, then I could at least visualize what is going on with my list and could correct it accordingly. That being said, how do I serialize an array or a list using Windows.Data.Json?
First of all, there's no built-in JSON-serializer that handles all the mapping for you. This is exactly what JSON.NET is doing for you. Therefore, you have to take the manual and long way.
To create exactly this result:
[{"id":130},{"id":131},{"id":132},{"id":133},{"id":134}]
You have to use the JsonArray class. For example, pass your jsonList object to a method like this:
public string ToJson(List<accountTypes> objectList)
{
var jArray = new JsonArray();
foreach (var at in objectList)
{
jArray.Add(ToJson(at));
}
return jArray.ToString();
}
Whereas you use this method to create a JsonObject for your class object itself (as manual step as well):
public JsonObject ToJson(accountTypes at)
{
var jObj = new JsonObject();
jObj.SetNamedValue("id", JsonValue.CreateNumberValue(at.id));
return jObj;
}
I'm trying to parse to a C# object a string containing a JSON that looks like that :
I know it's not really valid json but I can't choose it, it's sent by a device. That's why I've tried to replace the [] by {} to make it look like a valid object.
[2, "2", "text", {Object}]
I've created the following class:
public class MyClass
{
[JsonProperty(Order = 0)]
public int TypeRequest { get; set; }
[JsonProperty(Order = 1)]
public string UniqueID { get; set; }
[JsonProperty(Order = 2)]
public string Action { get; set; }
[JsonProperty(Order = 3)]
public JObject Payload { get; set; }
}
I want to parse the {Object} later (I need to know the "Action" property first because the object depends on the action).
So far I've done :
string userMessage = "[2, "2", "text", {Object}]";
if (userMessage.Length > 2)
{
// We need to remove the first [ and the last ] to be able to parse into a json object
StringBuilder sb = new StringBuilder(userMessage);
sb[0] = '{';
sb[sb.Length - 1] = '}';
userMessage = sb.ToString();
}
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
MyClass objectJSON = jsonSerializer.Deserialize<MyClass >(userMessage);
But it doesn't work I get the following exception:
Invalid object passed in, ':' or '}' expected. (3): {Object}}
I've also tried with JObject.Parse instead and I got:
Invalid JavaScript property identifier character: ,. Path '', line 1,
position 2.
Do you know how to do it? I would like to avoid having to split my JSON by commas and have the cleanest way to do it.
It's not really a valid JSON because of {Object} so I removed it. You can technically do json.Replace("{Object}", "something else") to make it easier. Because you deal with different types in array, it may not be a one step process. Here is an idea for you:
var json = "[2, \"2\", \"text\"]";
var array = JsonConvert.DeserializeObject<JArray>(json);
foreach (var item in array)
{
switch (item.Type)
{
case JTokenType.Integer:
// todo: your parsing code
break;
case JTokenType.String:
break;
// etc.
}
}
I used JSON.NET library to parse JSON. You can install it using nuget:
Install-Package Newtonsoft.Json
If you can, I'd recommend you to fix the JSON source to provide you with a valid JSON that can be parsed to an object without use of low-level classes like JToken, JArray, JObject etc.
This question already has answers here:
How to handle both a single item and an array for the same property using JSON.net
(9 answers)
Closed 4 years ago.
We're dealing with an json API result. Just to make our lives difficult the provider of the API returns on of the items as an array if there are multiple objects, or as a single object if there is only one.
e.g.
If there is only one object...
{
propertyA: {
first: "A",
second: "B"
}
}
Or if there are multiple:
{
propertyA: [
{
first: "A",
second: "B"
},
{
first: "A",
second: "B"
}
]
}
Does anybody have a good way of dealing with this scenario?
Ideally we'd like to serialize both to
public class ApiResult{
public ApiItem[] PropertyA {get;set;}
}
This works for the second example but of you encounter the first example you get a A first chance exception of type 'System.MissingMethodException' occurred in System.Web.Extensions.dll
Additional information: No parameterless constructor defined for type of 'ApiItem[]'.
I assume the class definition is as below
public class ApiResult
{
public ApiItem[] PropertyA { get; set; }
}
public class ApiItem
{
public string First { get; set; }
public string Second { get; set; }
}
You can deserialize the json into a dynamic variable, then check the type of d.propertyA. If it's JArray then propertyA is an array, so you can deserialize the json into a ApiResult. If it's JObject then propertyA is a single object, so you need to manually construct ApiItem and assign it to PropertyA of ApiResult. Consider the method below
public ApiResult Deserialize(string json)
{
ApiResult result = new ApiResult();
dynamic d = JsonConvert.DeserializeObject(json);
if (d.propertyA.GetType() == typeof (Newtonsoft.Json.Linq.JObject))
{
// propertyA is a single object, construct ApiItem manually
ApiItem item = new ApiItem();
item.First = d.propertyA.first;
item.Second = d.propertyA.second;
// assign item to result.PropertyA[0]
result.PropertyA = new ApiItem[1];
result.PropertyA[0] = item;
}
else if (d.propertyA.GetType() == typeof (Newtonsoft.Json.Linq.JArray))
{
// propertyA is an array, deserialize json into ApiResult
result = JsonConvert.DeserializeObject<ApiResult>(json);
}
return result;
}
The code above will return an instance of ApiResult for both json examples.
Working demo: https://dotnetfiddle.net/wBQKrp
Building upon ekad's answer, I made the code:
Shorter: as now you don't have map one by one every property inside ApiItem
Probably faster in the case of being already an Array (by not calling to both versions of JsonConvert.DeserializeObject with the same input of the json string)
Explicit about how to introduce other properties
Handling the error case of unknown type of our propertyA (the one that can be either an array or an object).
Notice that instead of JsonConvert.DeserializeObject, I call JObject.Parse, and then ToObject<> for only the part I need in that particular case:
static ApiResult Deserialize(string json)
{
JObject j = JObject.Parse(json);
var propA = j["propertyA"];
switch (propA.Type.ToString())
{
case "Object":
return new ApiResult {
PropertyA = new[]{propA.ToObject<ApiItem>()},
SomethingElse = j["somethingElse"].ToObject<string>(),
};
case "Array":
return j.ToObject<ApiResult>();
default:
throw new Exception("Invalid json with propertyA of type " + propA.Type.ToString());
}
}
The API is pretty much the same, but I've added SomethingElse (for showing how other properties can be easily handled with this approach):
public class ApiResult
{
public ApiItem[] PropertyA { get; set; }
public string SomethingElse { get; set; }
}
public class ApiItem
{
public string First { get; set; }
public string Second { get; set; }
}
Working demo: https://dotnetfiddle.net/VLbTMu
JSON# has a very lightweight tool that allows you to achieve this. It will retrieve embedded JSON, regardless of whether or not the embedded JSON is an object, or array, from within larger JSON objects:
const string schoolMetadata = #"{ "school": {...";
var jsonParser = new JsonObjectParser();
using (var stream =
new MemoryStream(Encoding.UTF8.GetBytes(schoolMetadata))) {
Json.Parse(_jsonParser, stream, "teachers");
}
Here we retrieve a "teachers" object from within a larger "school" object.
best way to Serialize/Deserialize to/from JSON is Json.NET
Popular high-performance JSON framework for .NET
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
//}
string json = #"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys
I'm facing a wierd problem when converting Json Unicode(?) to UTF8
"V\u00E4xj\u00F6" should be "Växjö"
Right now it seems like I've tried everything possible, but no luck.
Any coding ninjas out there that may sit on a solution? I'm sure it's fairly easy but still can't seem to figure it out.
Thank you
As Tomalak pointed out, it can be done using the System.Web.Helpers.Json.Decode method (no external libraries, .NET Framework). You need to build a simple JSON object to fetch the decoded text:
// helper class
public class Dummy
{
public String Field { get; set; }
}
//
var value = "V\u00E4xj\u00F6";
var sb = new StringBuilder();
sb.Append("{");
sb.Append(String.Format(#"""Field"" : ""{0}""", value));
sb.Append("}");
var dummy = Json.Decode(sb.ToString());
Console.WriteLine(dummy.Field);
// it works also without helper class
var obj = Json.Decode(sb.ToString());
Console.WriteLine(obj.Field);
The output is:
Växjö
Växjö
One possibility would be to use the Json.NET library to decode the string (or maybe for the whole JSON handling?). The deserializer decodes the string automatically. My test code looks like this:
// placeholder for the example
public class Sample
{
public String Name { get; set; }
}
//
var i = #"{ ""Name"" : ""V\u00E4xj\u00F6"" }";
var jsonConverter = Newtonsoft.Json.JsonConvert.DeserializeObject(i);
Console.WriteLine(jsonConverter.ToString());
//
var sample = Newtonsoft.Json.JsonConvert.DeserializeObject<Sample>(i);
Console.WriteLine(sample.Name);
The output is:
{
"Name": "Växjö"
}
Växjö
The web service I consume responces with json data.
it gives resultObject as array:
resultObject:[{object1}, {object2},...] if there more then one object
and it returns
resultObject:{object1} if there only one object.
for serializing in .NET I created a "static" structure of classes to map json schema. But if in one case i've got an array (list) of objects an in other case just one object, how is it possible to handle this situation?
I have found a plethora of ugly solutions to this one, but so far goes:
If you use the System.Web.Script.Serialization.JavaScriptSerializer you have very limited control. If the result data type is simple, you could simply use the DeserializeObject method; it will translate everything into Dictionary and the "resultObject" property will in the first case be a Dictionary while the latter case will turn it into an array of such dictionary. It will not save you the headache of the final translation, but you will get the data into dictionaries which could be considered a first step.
I also attempted to use the KnownTypes and the DataContractJsonSerializer, but alas the datacontract serializer needs "hints" in the form of specially named properties to aid it deserializing. (Why am I using the KnownType attribute wrong?). This is a hopeless strategy if you don't have any control of the serialization which I guess is the case for you.
So now we are down to the butt-ugly solutions of which trial-and-error is my first choice:
When using the ScriptSerializer the conversion will fail with an InvalidOperationException if anything is wrong. I then created two data types one with data-as-arrays and one where data is a single instance (the DataClass is my invention since you do not specify the data types):
[DataContract]
public class DataClass
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public int BirthYear { get; set; }
public override string ToString()
{
return "FirstName : '" + FirstName + "', BirthYear: " + BirthYear;
}
}
[DataContract]
public class ResultSingle
{
[DataMember]
public DataClass Data { get; set; }
}
[DataContract]
public class ResultArray
{
[DataMember]
public List<DataClass> Data { get; set; }
}
Using these data types it is possible to translate using
JavaScriptSerializer jSer = new JavaScriptSerializer();
var one = jSer.Deserialize<ResultSingle>(jsonWithSingleInstance);
var many = jSer.Deserialize<ResultArray>(jsonWithArray);
But this of course require you to known the data type in advance and you get two different result types. Instead you could choose to always convert to ResultArray. If you get an exception you should convert as ResultSingle and then instantiate the ResultArray and manually add the data object to the Data list:
static ResultArray ConvertJson(string json)
{
ResultArray fromJson;
JavaScriptSerializer jSer = new JavaScriptSerializer();
try
{
fromJson = jSer.Deserialize<ResultArray>(json);
return fromJson;
}
catch (InvalidOperationException)
{
var single = jSer.Deserialize<ResultSingle> (json);
fromJson = new ResultArray();
fromJson.Data = new List<DataClass>();
fromJson.Data.Add(single.Data);
return fromJson;
}
}
static void Main(string[] args)
{
var jsonWithSingleInstance = "{\"Data\":{\"FirstName\":\"Knud\",\"BirthYear\":1928}}";
var jsonWithArray = "{\"Data\":[{\"FirstName\":\"Knud\",\"BirthYear\":1928},{\"FirstName\":\"Svend\",\"BirthYear\":1930}]}";
var single = ConvertJson(jsonWithSingleInstance);
var array = ConvertJson(jsonWithArray);
}
I do not say this is a beautiful solution (it isn't), but it should do the job.
You could also look at json.net which seem to be the json serializer of choice in .NET: How to install JSON.NET using NuGet?
Well, my service provider finally said that it is really a bug.
http://jira.codehaus.org/browse/JETTISON-102
says that is it because of java version that they use.