Adam Lonsdale
Adam Lonsdale

Reputation: 37

JSON Deserialization in .NET

I've had a look at a few threads but what I'm aiming for I can't seem to find.
I have the following JSON strings returned:

On success:

{"success":{"username":"key"}}

On Error:

{"error":{"type":101,"address":"/","description":"link button not pressed"}}

I need to be able to de-serialize these into a class and determine whether I've got an error or a success message to carry on doing it. Any ideas on how to achieve this?

thanks,

Adam

Upvotes: 2

Views: 557

Answers (3)

L.B
L.B

Reputation: 116108

No need to declare a lot of tiny classes. dynamic keyword can help here.

dynamic jObj = JObject.Parse(json);
if (jObj.error!= null)
{
    string error = jObj.error.description.ToString();
}
else
{
    string key = jObj.success.username.ToString();
}

Upvotes: 1

Knaģis
Knaģis

Reputation: 21475

One option is to use http://nuget.org/packages/newtonsoft.json - you can either create your own custom class to deserialize into or use dynamic as the target type.

var result = JsonConvert.DeserializeObject<Result>(jsonString);

class Result
{
    public SuccessResult success { get; set; }
    public ErrorResult error { get; set; }
}

class SuccessResult
{
    public string username { get; set; }
}

class ErrorResult
{
    public int type { get; set; }
    public string address { get; set; }
    public string description { get; set; }
}

If you need just to check for success, it is possible to just check result.StartsWith("{\"success\":") to avoid unnecessary parsing. But this should only be done if you have guarantee that the JSON string will always be exactly like this (no extra whitespaces etc.) - so it is usually only appropriate if you own the JSON generation yourself.

Upvotes: 1

user15741
user15741

Reputation: 1412

This answer covers most options, including rolling your own parser and using JSON.Net:

Parse JSON in C#

You could also just write a regex if the format is going to be that simple...

Upvotes: 0

Related Questions