At the moment, I'm trying to figure out how to save a Jint.NET JavaScript environment to file, so I can load it again later.
However, I'm having major trouble trying to serialize/deserialize the Jint.Native.JsValue class. Since it has no constructor, Newtonsoft doesn't like deserializing to it, and when serializing, it ignores all private properties, resulting in only the Type field being saved.
string saved = JsonConvert.SerializeObject(someJsValue); //output: {Type: x}
JsonConvert.DeserializeObject<JsValue>(saved); //error: no constructor
Is there any way around this so I can load/save this properly?
Related
I have a class with properties of type object, such as:
public object Meta {get; set;}
Previously, I stored these properties without serialization, which resulted in an exception when attempting to access them due to deserialization errors. To resolve this issue, I now serialize these fields before inserting the documents into the database. This solution works well, as they are deserialized in the front-end. However, I am curious if there is a more efficient method, such as a custom serializer, that could allow these properties to be stored in the database as an object, rather than a long and unreadable string.
if we have this object for example:
"meta":{"description": "some long text here", "someValue" : "another long text here","anotherValue":"some really long text here"}
It would be quite nice and beneficial to be able to easily access and read individual fields within the meta object separately from the database.
I have binary serialized objects in database. They are serialized with protobuf.
Now I need to generate some viewer to see the content of Database.
So, i read stream from database and deserialized it back to the objects.
It works and the result is list of objects:
var dbData = readData(someType);//it is IList collection
Now, I would like to save this list of objects to file to see the content of database. I thought it would be the best to save it to xml. So, i have tried:
var serializer = new XmlSerializer(dbData.GetType());
But i get an error: Cannot deserialize type 'My.Entities.IdBase' because it contains property 'Key' which has no public setter.
What now? I can't change the class definitions to have setters.
Should i save objects to json or plain text instead? Or should i extract all properties and values and save it to some xml? Any code example?
JSON.NET would be the answer here. You can find it in nuget. Use it like this:
JsonConvert.DeserializeObject<T>(input);
Hi I'm quite new to C# and I'm trying to make a text editor that saves and loads Plaintext formats. I've used NewtonSoft.Json NuGet package, but I'm getting an error. I've stated a string called textToLoad, which is set to a JsonConvert.DeserializeObject. Only thing is, it says it can't convert an object to a string! I tried toString(); but it still had the same error.
It is kind of hard without the code. The process of serializing and deserializing is pretty straight forward using Json.Net. So this is an example from their documentation:
YourType yourObject= new YourType();
yourObject.Property="something";
string output = JsonConvert.SerializeObject(yourObject);
//For some reason you want this to be string, but is the type you serialized in the first place
YourType textToLoad= JsonConvert.DeserializeObject<YourType>(output);
This outlines the basic works of serializing and deserializing. But we don't really know the details of your implementation.
Hope it helps.
You can't deserialize into a string like that. At simplest form you started with JSON in the form of:
{ value: "someString" }
If you want something out of it, you must deserialize and then get the value from it.
dynamic foo = JsonConvert.DeserializeObject<dynamic>(theJson);
var textToLoad = foo.value.ToString();
You must deserialize to something in order to inspect and get properties from it.
[Edit] - Perhaps I'm not understanding. But if you share code, I'll update my answer.
I'm building a game with Unity3D. I have a class called GameInstance containing all the current game instance data in it. It contains multiple sub classes for instance the Player property would return a Player object.
Yet all objects are simple key/values objects, it's only data. Now I'd need to serialize all of this and save it to a file so I can reload it to restart the game where it left.
That's what I basically intent to do, maybe somebody would have a better suggestion but yet that's the most flexible option I found.
I used .NET XML object serialization in the past but it's been a while and I'd need to have a more direct advice on this. Should I serialize to XML or JSON for example?
TL;DR: I want to serialize a whole class with all its content with C#/.NET in a Unity3D project. How should I proceed?
Thanks!
I personally prefer json. If you're using json.NET this will be as simple as;
string json = JsonConvert.SerializeObject(MyObject);
or to compact it;
File.WriteAllText("./myfile", JsonConvert.SerializeObject(MyObject));
Then to deserialize you would just do;
MyObject obj = JsonConvert.DeserializeObject<MyObject>(File.ReadAllText("./myfile"));
EDIT: In response to the exception, you want to use this overload which allows you to change the serilization settings;
JsonConvert.SerializeObject(ResultGroups,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
I'm a bit out of my element. I've used xsd.exe to create an xsd schema from an xml file, and then to create a C# class from that xsd. That all seems to work fine.
At the moment I'm just trying to get the XML deserialized. The file I'm deserializing if the very same file I used to build the class originally. Here's my code:
String xsdPath=#"C:\Users\tol56881\Documents\dnd4e.xsd";
String xmlPath=#"C:\Users\tol56881\Documents\dnd4e.xml";
String xsdNamespace="";
//Validation stuff
XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
XmlValidatingReader vr = new XmlValidatingReader(xmlPath, XmlNodeType.Element, context);
vr.ValidationType = ValidationType.Schema;
vr.Schemas.Add(xsdNamespace, xsdPath);
while (vr.Read()) ;
//Actually reading the file
TextReader tr = new StreamReader(xmlPath);
D20Character character = (D20Character)(new XmlSerializer(typeof(D20Character))).Deserialize(tr);
It compile fine, but when I try to run it I get the an error that's repeated for four different objects. I've given an example below, changing the names of the objects.
Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'Namespace.ObjectName[]' to 'Namespace.ObjectName'
error CS0029: Cannot implicitly convert type 'Namespace.ObjectName' to 'Namespace.ObjectName[]'
So it seems like the program is trying to go from array to object and back to array, but I'm not really sure. The auto-generated class code is a huge mess that's difficult to wade through. I'm hoping that maybe there's something simple I'm missing here.
Thanks!
I managed to fix this. Each of the four objects in question were generated as doubly-indexed arrays, such as:
private loot[][] lootTallyField;
and
public loot[][] LootTally
{
get
{
return this.lootTallyField;
}
set
{
this.lootTallyField = value;
}
}
All I did was remove one set of brackets, and it all seems to be working fine. No problems with deserialization and a quick inspection of the deserialized object makes it look like the data was loaded correctly.
private loot[] lootTallyField;
and
public loot[] LootTally
{
get
{
return this.lootTallyField;
}
set
{
this.lootTallyField = value;
}
}
Still not sure why xsd.exe made these doubly-indexed if they're not supposed to be. I feel like I'm still missing something, hence why this question is still open.
Particularly, if I ever need to re-generate this code, then I'd need to reapply the fix, which kind of defeats the purpose of using a partial class in the first place...
There is a problem on xsd.exe tool, I will try to explain.
If you have a complexType with a sequence inside that has a child complexType with a sequence and the first one does not have any other elements / attributes, then the generated class will have only 1 generated type, instead of 2 and it will be a double array.
If you make the double array into a single array, you will be able to deserialize your xml just fine.
HOWEVER this will produce the following unexpected result.
If your xml looks like the below.
<root>
<loot>
<tally>value1</tally>
<tally>value2</tally>
</loot>
<loot>
<tally>value3</tally>
<tally>value4</tally>
</loot>
</root>
Then your deserialized object, in the lootTally array would only contain the value3 and value4 items instead of having all 4.
So you have 2 options to fix this correctly:
Alter the xsd file by adding a dummy in the first sequence, and run xsd.exe again, so that when it generates the class it will not create a double array, and then you can delete the dummy attribute from the class.
Alter the generated class, add a new class named loot which will contain an array of tally objects which you already have (and only need to alter the name).
Please note that in option 2 you may have to change some declarations if you have an XmlArrayItemAttribute to XmlElementAttribute.
Hope this helps