Validating result of JsonConvert.DeserializeObject (think "try parse") using JSON.Net - c#

I have incoming messages that I need to try and parse in my own objects structure. SOme of these are well formed JSON obejcts and some are just nonsense.
I use JsonConvert.DeserializeObject<MyObject>(incmoingString); to do this. This however sometimes gives me a exception when the incoming is total garbage. Other times I get a non-complete object structure when the incoming string is kind of OK - and finally it sometimes work.
I've wrapped the conversion in a try/catch and than manually validate that I've gotten the properties I need to the deserialized result.
Is there a better way to do this?

Json.NET supports JSON Schema. You could create a schema with all the required properties marked and validate incoming JSON against it before deserializing.

Related

Serialize but not deserialize fields/properties in XML, JSON and (particularly) YAML?

I have a set of objects that contain fields & properties that need to be inspectable in the output of serialization but not read back in when deserialized.
This is purely for debugging/confirmation purposes. We are creating hundreds of files and I want to spot check that serialization is occurring correctly by adding supplementary information. I do not want this supplementary information to be read in during deserialization - it's impossible to do so in fact.
I also need to do this with equal facility across different serialization formats, so we can assess which one is working best. I have a generic serialization approach where the desired format is passed in as an argument, so don't want anything too messy or intricate for each different format.
I've hunted around and found various things on related topics - mostly to do with the opposite: not writing certain fields during serialization. What's out there seems to be quite complicated and at times hacky.
Is it possible to serialize an object differently to deserializing it using Json.Net?
JsonConvert .NET Serialize/Deserialize Read Only
Serialize Property, but Do Not Deserialize Property in Json.Net
Also it appears any approach is inconsistent between serialization formats. i.e. unlike the [*Ignore] attributes, there are no [*SerializeOnly] attributes (where * = JSON, XML, YAML).
Is there an easy way to do this across these serialization formats? Is there a single family of attributes that can help? Or is it idiosyncratic and hacky in each case?
I have tested and applied this only to XML serialization, but it works for me:
When I want a property to be serialized, but not read back, I just declare an empty setter.
public String VersionOfApplicationThatHasWrittenThisFile
{
get
{
return "1.0";
}
set
{
// Leave empty
}
}

How to get and deserialize value created with RedisOutputCacheProvider?

I'm using Microsoft.Web.Redis.RedisOutputCacheProvider for output caching in Redis. The task is to retrieve manually value from the Redis database and deserialize value for further processing the original HTML.
I tried StackExchange.Redis.IDatabase - can get value by key with StringGet() method, but the problem is that it's serialized. Any thoughts regarding above ?
That's because RedisOutputCacheProvider by default, serializes in a binary format provided by the BinaryFormatter class.
So you need to deserialize it in the same way OR use a custom serialization method on RedisOutputCacheProvider.
Check its configuration wiki with the instructions to use a custom serializer.

How to parse a collection of unknown JSON object types inside a known JSON structure using JSON.Net?

I am attempting to parse some JSON that has a known top level schema. However inside the schema is one JSON object that can contain various types of JSON objects.
Example
{
"knownfield1": data,
"knownfield2": data,
"knownfieldcollection":
{
"fieldofunknowntype1": "string data",
"fieldofunknowntype2":
{
"subunknownfield1": "string data",
"subunknownfield1": null
},
"fieldofunknowntype3": null
}
}
I would like to make an object that contains a mapping of the known fields, but can read the unknown fields in dynamically. I was trying with Json.Net JToken and JObject, but I could not get it to work. I kept getting recursive JToken exceptions.
Any pointers on this would be great. Thank you.
Exception I am getting:
Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data
contract which is not supported. Consider modifying the definition of
collection 'Newtonsoft.Json.Linq.JToken' to remove references to itself.
--edit--
Mistyped Collection for object, fixed that.
We have a winner. DBC hit the nail on the head. I had some left over WFC deserialization and it was causing problems. As soon I made sure all the DataContract code was completely cleared out and replaced everything with proper JSON.Net tags and calls, it worked wonderfully.
Thank you everyone for the support.

Send a complex object over JSON and then rebuild it on another pc

Can I use JSON to send a complex object from one pc to another?
From my understanding of JSON you can just stringy that object, then send the string to the other pc and then destringify it and rebuild the object again.
But now how does it know what object I have sent it? cause I could send it object A or object B ?
Is there a way to find out what object I have sent it? Or is part of JSON knowing what type of object you are going to receive?
Can I use JSON to send a complex object from one pc to another?
Yes
But now how does it know what object I have sent it? cause I could
send it object A or object B ?
The receiver knows when it deserialises the Json. The receiver needs to know what the Json will look like or dynamically deserialise it if it cannot know. See this SO answer on dynamically deserialising.
dynamic something = JsonConvert.DeserializeObject(json);
If as client you use as an instance of a class like Spring RestTemplate, you can tell it which class it should expect the JSon to be an instance of, and convert it accordingly.
http://www.springframework.net/rest/doc-latest/reference/html/resttemplate.html
JSON is the string representation of data.
You either know what the other side expects or need to send additional meta-data.
Very often you know exactly what kind of object has been sent.
Adding additional meta-data could easily be done automatically (and I am sure there are a lot of libraries available):
{
class: A
entity: {...}
}
But now how does it know what object I have sent it? cause I could
send it object A or object B ?
The other side should be aware to the fact that a JSON object has been received in a string format and accordingly, to parse or deserialize it properly, just like in the following example, which takes a JSON string and parse it to JSON or C# object:
In JavaScript:
var jsonObj = JSON.parse(yourJsonString);
In C#:
dynamic jsonObj = JsonConvert.DeserializeObject(yourJsonString);
In addition, if it's an HTTP request, you can specify the content-type to: application/json.
This way, the receiver side could analyze it and understand it is a JSON string.
Read more:
JSON.parse()
JavaScriptSerializer.DeserializeObject Method

.NET deserialization of json fails if __type is not first in property list

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.

Categories

Resources