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.
Related
Someone send JSON to me. It has same format each time. It can be deserialised into dynamic object with var dyn = JsonConvert.DeserializeObject<dynamic>(rawJson);. Documentation is bad for my current version or JSON provider while I want to have code-hilighting on all the fields I get.
How to get C# class code from dynamic object so that I could then deserialise into that generated type instead of dynamic object with var oldschool = JsonConvert.DeserializeObject<GeneratedTypeFromDynamicObject>(rawJson);?
Generating a type at run-time isn't going to help you much because you need the type at compile time in order to get early binding, type safety, and Intellisense. A much more practical idea would be to do the following:
Get a representative sample of a JSON string from your logs.
Paste the JSON into a class and save it as c# code in your project.
Start using the class as the type argument to your deserialization call.
After you do this, you will have the correct class in your code base and you can compile against it. If the folks that send you the JSON decide to change the message, any new fields will be ignored. If they start removing things though then you have problems, just as if they had changed the WSDL for a SOAP service. You will have to repeat the above steps, and correct any breaking changes in your code. The nice thing is that you will have the breaking changes to guide you at compile time :)
First of all I have checked all old questions and found this one useful: Reading dynamic attributes of json into .net C# but wasn't so useful in my case, I'm missing something not sure what is it!
I'm trying to read dynamic JSON with nested dynamic attributes, here is the JSON:
{"data":{"cart":{"seats":{"3B00535EF2414332":{"212":{"6":["22","21"]}}}}}}
Please keep in mind that 3B00535EF2414332, 212 and 6 are dynamic each time I get this JSON.
In C#, I don't know how should I set the attributes as I need to provide a class with properties with exact the same name of the object to deserialize this object. I though about parsing it to dynamic object in C# and try to call it, but still can't as the only known value for me each time is 3B00535EF2414332 but other 2 dynamic properties are not known to me, I need to retrieve them.
I though about the dictionary way, but I couldn't create it right. Actually, I didn't understand it right.
Thanks for your time.
You can try this:
var results = JObject.Parse(json)
["data"]["cart"]["seats"]
.Children<JProperty>().First().Value
.Children<JProperty>().First().Value
.Children<JProperty>().First().Value
.ToObject<int[]>();
EDIT: you can also use this to retrieve the values along with the path names:
var seats = JObject.Parse(json)["data"]["cart"]["seats"].Children<JProperty>();
var unknown0 = seats.First();
var unknown1 = unknown0.Value.Children<JProperty>().First();
var unknown2 = unknown1.Value.Children<JProperty>().First();
// unknown0.Name -> 3B00535EF2414332
// unknown1.Name -> 212
// unknown2.Name -> 6;
// unknown2.Value.ToObject<int[]>() -> [22,21]
I am currently trying to save a list in Xamarin forms. I use this code snippet:
var list = new List<myClass> ();
Application.Current.Properties["myList"] = list;
await Application.Current.SavePropertiesAsync();
When I then close the app and use this code...
if (Application.Current.Properties.ContainsKey("myList"))
{
}
...I cannot reach this if statement.
I read something about people having issues saving a list with this solution but they solved it by converting it to a string. I am a bit unsure on how to do this. If I do this...
Application.Current.Properties["myList"] = list.ToString();
...the app crashes.
I saw that there is a plugin called "Settings" that I might need to use instead in case there isn't a solution to this problem but I would prefer to work with my current code if possible.
The Properties dictionary can only serialize primitive types for
storage. Attempting to store other types (such as List can
fail silently).
It means that you can't save List because it's not a primitive type of object. You can serialize it to JSON string for example then it will work. Code example:
var jsonValueToSave = JsonConvert.SerializeObject(myList);
Application.Current.Properties["myList"] = jsonValueToSave;
await Application.Current.SavePropertiesAsync();
Don't forget to deserialize JSON to List<string> when loading the value back.
Note that yourList.ToString() will not work in this case. More info here.
P.S.: Get familiar with the official documentation & check this post on another related thread.
I send json objects to DotNet Service in format
{"__type":"EntityItem#ru.test.com","name":"sample"}
And on Net service i got object EntityItem and all good.
But if __type will not first in list properties then it's get error parsing object. Next version JSON crashes
{"name":"sample","__type":"EntityItem#ru.test.com"}
Does exists solution how to fix it?
It's called "type hints". Here is link http://msdn.microsoft.com/en-us/library/bb412170.aspx
and qoute
Note that the type hint must appear first in the JSON representation. This is the only case where order of key/value pairs is important in JSON processing.
It's so sad.
I'm building a Foursquare app for Windows Phone 7. It's working nicely with HttpWebRequests and I'm receiving JSON objects perfectly. I'm using the DataContractJsonSerializer(type) method. But when deserializing this JSON to the object I want, It all goes well until I there's and array of objects, where I don't know which object-type to expect (also don't know the amount & order of objects). But I do need to define this type when deserializing in the method DataContractJsonSerializer(type).
Let me show you a snapshot of JSON which causes the trouble:
notifications":
[{
"type":"notificationTray",
"item":{
"unreadCount":0
}
},{
"type":"message",
"item":{
"message":"OK! We've got you # Strandslag 4. You've been here 2 times."
}
}]
So I'm deserializing this to an array of Notification objects, with two memers: "public String type" and an "public Object item". I can't know which, and how many, Notification's there will be in the array (and thus of what type the 'item' member must be). As you can see in the JSON, the first notification has an item of type int, but the second notification's item is of type string. But I need to know that for the deserialization... Or else it just stays null.. So I cant cast it to the correct type..
Does anyone knows how to solve this nicely?
Hmmm not 100% sure this will answer your question but can you not use javascript to convert whatever the object is into a string and then manipulate it that way?
Something like:
var value = whatever[number].toString;
This would give you a string you can work with. You could then try to parse it back to an int.
var valueInt = parseInt(value);
Then use an IF statement to see if the valueInt exists or not to determine what kind of value the first object has.