First of all; I'm using Newtonsoft.Json to deserialize JSON into objects like this:
JSON:
[{"number":22041}]
Order Object
[JsonProperty("number")]
public string OrderNumber { get; set; }
However, depending on which version the 'other' side is on, the Json may change into
[{"order_number":22041}]
So I'd actually like to pre-define "number" and "order_number" to both deserialize into my OrderNumber.
Is there a way to achieve something like the following (that actually works)
[JsonProperty("order_number")]
[JsonProperty("number")]
public string OrderNumber { get; set; }
I could write another class that has the same properties but with other JsonProperties depending on the Version they are on, but that seems like something to try last, unless there is no possible way to do this easier.
Update
I agree that this question is a duplicate of the question above. However since the given keys in the JSON changes significantly, I will be making duplicate objects (OrderV1 , OrderV2 as example).
Simply replacing some characters into other ones will not be enough in my case.
Related
I want to send some part of class to server.
sending Info
[Serializable]
public class SendingInfos
{
public string tempID;
public string playerLettersInHand;
public string playerLettersMiddle;
public int playerBet;
public string playerLetterSent;
}
currently temID and playerBet has value while rest of them null.In this case, if i use
string jsondata = JsonUtility.ToJson(sendingInfos);
this and send it. Do i send the part of class which isnt null or all of it?
Is there any other option to send part of it? like
string jsondata = JsonUtility.ToJson({ sendingInfos.tempID, sendingInfos.playerBet });
Edit: the reason i want to send somepart of class to server is,to keep server network traffic at low as much as possible. Also, i might do this by dividing the class to 2 class.however if there is , easier way , i want to do that.
Normal operation in this case is just to serialize the whole object. That way you make sure it can be deserialized without additional settings. NULL should be handled automatically AFAIK, so when serializing again you should get the same object back (with all values set to NULL or an actual value)
You would not normally send only half of an object, because you maintain a contract between the sender and the receiver for the full object, and not half of it or one third. That seems a bit odd and i cannot figure out why you would want this.
I have a service call that accepts the following model:
public class ServiceModel {
public DataModel dModel {get; set;}
public JObject schema {get; set;}
}
The DataModel is responsible for holding data that will be used to populate user defined schema (see below).
The schema is a user defined (at runtime) dynamic json structure that contains tokenized values like this. Being that it's user defined, it can be deeply nested.
{
"id": "<tokenized_id>",
"hero":{
"heroName": "<tokenized_heroName>",
"heroType": "<tokenized_heroType>",
"heroSkill": "<tokenized_heroSkill>",
"heroArmor": {
"armor_id": "<tokenized_armorId>",
...
}
}
}
What I want to do is pull data from the DataModel and replace the corresponding tokenized value with it. The tricky part comes from the possibility of deeply nested objects
My first idea is to just flatten the schema into a string and doing a Find/Replace on the entire string but I'm curious if there's a more elegant way.
There's the option of working with JObjects or even Dictionary but neither provide a nice way to access nested objects. I believe I would need to use recursion which could get ugly.
Are there betters ways to accomplish this?
Let's say I have some json similar to the following:
"productdetails": [["loading"], ["loaded"], ["detailkey", "detailvalue"]]
The formatting is out of my control, and I need to be able to access the 'loading' and 'loaded' parts to make sure the data was loaded properly before moving on further to continue work with the data. I haven't been able to figure out how to setup nested properties that also have no key.
Edit: Should have noted, 'loading' and 'loaded' can be different things and there can be varying amounts of status update arrays before the details or other messages. So, the above could be returned, or something like this:
"productdetails": [["loading"],["empty"],["created"],["loaded"],["detailkey", "detailvalue"]]
Edit 2: Excuse the errors in my json syntax, the colons have been switched out to create a properly syntaxed example.
This is just a two-dimensional array, which can be represented as a list of list of string
You should be able to deserialize it to this object:
public class RootObject
{
public List<List<string>> productdetails { get; set; }
}
I recomment Newtonsoft's Json.Net parser.
Example:
string jsonString = "{\"productdetails\": [[\"loading\"], [\"loaded\"], [\"detailkey\", \"detailvalue\"]]}";
RootObject obj = JsonConvert.Deserialize<RootObject>(jsonString);
I use an API which returns JSON. I'm having trouble with accessing elements when they are not in an array.
My JSON looks like this:
On the JSON of 2, I can access the elements with
dataJson.Storingen.Ongepland.Storing.#elementName#
However, when I use the JSON of 1, I get the following exception:
Additional information: Newtonsoft.Json.Linq.JProperty does not contain a definition for Traject
The structure of second json is different about the first.
In second case, you should use dataJson.Storingen.Ongepland.Storing[0].#property to access the property that you want.
But if you want to roll up in your array, just to use a for
The two JSONs on that picture are not similar in architecture. The first one has a nested "Storing" object, that has several properties, but in the second case, "Storing" became an array of objects. Is it possible that your object model that you're trying to map to tries to parse this array as a single object?
If so, then I think you need to change the type of "Storing" in your model to an array. You will be able to get the elements then like this:
dataJson.Storingen.Ongepland.Storing[0].#elementName#
I know this is an old post, but I thought maybe I could just share my thoughts on this question number 1 I believe, just in case someone from the future saw this.
1st. Create two classes as such:
public Storing Test {get; set;}
public class Storing
{
public string id {set; get;}
public string Traject {set; get;}
public string Periode {set; get;}
}
2nd. In the main program, deserialize the JSON and call the object as such
TestCase list = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<TestCase>(*your web API uri*);
Console.WriteLine ("id:{0}, Traject{1}, Periode{2}", list.Id, list.Traject, list.Periode);
I use the XML format to keep settings for my C# project.
Theses XMLs are deserialized into C# classes.
Often enough, a class design changes but I forget to update the XML. Deserialization usually works fine and missing elements just get their default values.
This behavior is not desirable for me. I would like to have automatic validation that asserts the class and the XML have exactly the same structure.
I know I can create XML schemas (e.g using XSD) for my classes, but I could not figure an easy way to do it automatically and not manually (recall my classes' design changes often). Also, this solution seems kind of unnatural. I do not really need XML schemas. I have classes and their serialized XML instances. Adding schemas seems superfluous.
Thanks a bunch.
Why you don't create a method in your settings class that can be invoked after xml deserialization?
Suppose you have a class like this:
class Settings {
public string Property1 { get; set; }
public int Property2 { get; set; }
public bool IsValid() {
if(string.IsNullOrEmpty(Property1)) return false;
if(Property2 == 0) return false;
}
}
Using IsValid you can check everything in your class. Please, remember that this is an example. I think is good to manage object validation. If you change something in the time, you can edit the validation method to check new situations.
To go with Roberto's idea and take it a step further you could get all the properties via reflection:
var props = yourClass.GetType().GetProperties()
Inside of your validation function you could loop over those properties with:
foreach(var prop in props) // or foreach(var prop in yourClass.GetType().GetProperties())
{
//...Validation of property
}
If one of the properties has its standard-value you throw a custom exception that tells you you did not update your XML-file properly.
You can implement this using Version Tolerant Serialization (VTS) https://msdn.microsoft.com/en-us/library/ms229752%28v=vs.110%29.aspx
The Serialization Callbacks is what you are looking for in the VTS capabilities