2

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

user1500049
  • 993
  • 7
  • 15

3 Answers3

1

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.

Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • 1
    Wow... I almost upvoted, but then you suggested not parsing the JSON and expecting a very specific string that would fail if the JSON creation added spaces anywhere. Tempted to vote down for that reason... – Ruan Mendes Nov 06 '12 at 19:51
  • it always depends on the situation - if you are sure how the JSON string is generated, then you can do that. will edit the answer to include the proper warning – Knaģis Nov 06 '12 at 19:52
  • 1
    Please don't code or suggest expecting a specific JSON format, it's not JSON in that case, it's your own formatting that mimics JSON and may break when trying to interact with JSON. You're asking for incompatibility problems down the road if you do this. Remember that most JSON generators give you the pretty print option for debugging – Ruan Mendes Nov 06 '12 at 19:53
1

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();
}
L.B
  • 114,136
  • 19
  • 178
  • 224
0

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...

Community
  • 1
  • 1
user15741
  • 1,392
  • 16
  • 27