Unity serialize some part of class to json - c#

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.

Related

Deserialize different JSONs in to one class

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.

Load/Deserialize faster Json data to C# object

In my code I use Newtonsoft.Json :
MyCSharpTargetClass foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);
The content of the json_string is constant (loaded from a file that never changes).
The functionality is fine but the deserializing process is slow at execution.
My question: is there a way to pre-calculate the object, or to put it in a constant*, or whatever to speed up the execution ?
Note: Actually I didn't manage to put it a constant the result of JsonConvert.DeserializeObject<...>(), but I'm new to C#, so I should have missed something.
Thanks for your help
[EDIT] Solution : Force the Newtonsoft assembly to be loaded at the start of the application.
You do it the same way you would any other object: make it a private member variable, whose value is computed exactly once:
private static readonly MyCSharpTargetClass foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);
Or do it in the constructor:
private readonly MyCSharpTargetClass foo;
public MyObject()
{
foo = JsonConvert.DeserializeObject<MyCSharpTargetClass>(json_string);
}
That way the work to deserialize the string is done exactly once.
There's actualy not a lot of thinks you can do to speed this up.
Using ignore attribute, so this fields will not be added. Use this for some properties or calcualatable properties/fields, which can be recalculated later.
Hope this link helps :
https://msdn.microsoft.com/en-us/library/system.runtime.serialization.ignoredatamemberattribute.aspx
Using threads to read/write your objects, if you can customize your data into many files and serialize/deserialize in threads.
Deserialization JSON algorithms requires to read whole file about 3 times.
For better perfomance you can use YAML. Simple as XML/JSON, but with much better perfomance, since it reads file only 1 time.
Using shorter DataMember names to fields
[DataMember(Name = "id")]
public int MyObjectForSomethink{get;set;}

Access elements in JSON array

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);

How to Optionally exclude a class member when serializing to XML

I just took over a fairly large project. One of my tasks is to modify the code that gets rate quotes from FedEx. Currently, in order to get a set of rate quotes for a shipment that includes quotes for each "ServiceType" (Ground, 2-day, overnight, etc.) the code makes one call for each type. FedEx offers a web service that is used to get this information. After doing a little research, it looks like this web service can return multiple ServiceType quotes with a single round-trip. To do this, I'm supposed to "leave the service type out of the request." (Here's the question that pointed me in that direction.)
So I know that I can exclude the service type property from the serialization by decorating the property with, [System.Xml.Serialization.XmlIgnoreAttribute()]. But how can I do that only when I want results for all the ServiceType values and still be able to pass a single service type for the cases where I know what shipping method the user wants?
EDIT: FedEx's documentation indicates that this field is optional. Some basic testing shows that excluding it from the request with the XmlIgnoreAttribute does return data for multiple ServiceTypes.
If you implement a public bool ShouldSerializeXXX() function alongside the XXX property being serialized, XmlSerializer will ignore the corresponding XXX property when the function returns false. You'll have to have some basis for setting this (maybe the XXX property can be null? or you can grab some other state to make the decision.)
So, something along these lines:
public class MyClass
{
public ServiceType? ServiceType { get; set; }
public bool ShouldSerializeServiceType() { return ServiceType.HasValue; }
}

How do I serialize a dynamic object?

I want to make a Configuration Data Manager. This would allow multiple services to store and access configuration data that is common to all of them.
For the purposes of the Manager, I've decided to create a configuration class object - basically what every configuration data entry would look like:
Name, type, and value.
In the object these would all be strings that discribe the configuration data object itself. Once it has gotten this data from its database as strings, it would put it into this configuration object.
Then, I want it to send it through WCF to its destination. BUT, I don't want to send a serialized version of the configuration object, but rather a serialized version of the object discribed by the configuration object.
The reason I'd like to do this is so that
The Data Manager does not need to know anything about the configuration data.
So I can add configuration objects easily without changing the service. Of course, I should be able to do all of the CRUD operations, not just read.
Summary:
Input: string of name, type and value
Output: Serialized output of the object; the object itself is "type name = value"
Questions:
Is this a good method for storing and accessing the data?
How can I/can I serialize in this manner?
What would the function prototype of a getConfigurationData method look like?
I have decided to go in a different direction, thanks for the help.
Is this a good method for storing and accessing the data?
That is difficult to answer, the best I can give you is both a "yes" and a "No". Yes, It's not a bad idea to isolate the serialization/rehydration of this data.... and No, I don't really care much for the way you describe doing it. I'm not sure I would want it stored in text unless I plan on editing it by hand, and if I'm editing it by hand, I'm not sure I'd want it in a database. It could be done; just not sure you're really on the right track yet.
How can I/can I serialize in this manner?
Don't build your own, never that. Use a well-known format that already exists. Either XML or JSON will serve for hand-editable, or there are several binary formats (BSON, protobuffers) if you do not need to be able to edit it.
What would the function prototype of a getConfigurationData method look like?
I would first break-down the 'general' aka common configuration into a seperate call from the service specific configuration. This enables getConfigurationData to simply return a rich type for common information. Then either add a extra param and property for service specific data, or add another method. As an example:
[DataContract]
public class ConfigurationInfo
{
[DataMember]
public string Foo;
...
// This string is a json/xml blob specific to the 'svcType' parameter
[DataMember]
public string ServiceConfig;
}
[DataContract]
public interface IServiceHost
{
ConfigurationInfo GetConfigurationData(string svcType);
}
Obviously you place a little burden on the caller to parse the 'ServiceConfig'; however, your server can treat it as an opaque string value. It's only job is to associate it with the appropriate svcType and store/fetch the correct value.

Categories

Resources