0

I'm facing problems when I try to deserialize a JSON that is not coming always in the same exact format. The JSON I'm getting is something like this (trimmed for clarity):

{  
  "header": {  
    "code": "4",  
    "description": "Input Validation Error",  
    "errors": {  
      "code": "100",  
      "description": "externalServiceCode: must match '[A-Za-z0-9_]+'"  
    }  
  },  
  "externalCode": "259716_TRAVELAC"  
},  
{  
  "header": {  
    "code": "4",  
    "description": "Input Validation Error",  
    "errors": [  
      {  
        "code": "100",  
        "description": "Currency not valid"  
      },  
      {  
        "code": "100",  
        "description": "Can not be empty"  
      }  
    ]  
  },  
  "externalCode": "259716_TRA"  
}  

As you can see, the "errors" value could be simple:

 "errors":{"code":"1","description":"description"}  

or may come as an array:

 "errors":[{....},{....}].  

I don't have any control on the JSON format (the service where I'm getting it is made by another company).

The thing is that I couldn't find a simple way to parse this JSON into C#. I made the custom classes, and if I try it as a simple object, I miss the data if there are multiple errors, and if I consider it as an array, I don't get anything if the JSON comes with only one error (please note the missing enclosing brackets [ ] in the errors part when there is only one).

Is there any way to solve this? I've tried several approaches, but nothing seems to work.

I4V
  • 34,891
  • 6
  • 67
  • 79
prf
  • 9
  • 1
  • Which deserializer are you using? Json.NET? Other? Anyway, consider converting/normalizing the single "error" to an array of "error" and treat both the same (as a sequence of error objects). How this is achievable will differ by parsing mechanism used and/or if a separate JSON->JSON normalizer is used. – user2246674 Sep 03 '13 at 23:06
  • I'v tried using both: JavaScriptSerializer and DataContractJsonSerializer. I'm trying to avoid use third party libs as Json.Net. I know that the easy way is to normalize the single "error" as an array, but this is done by another company and I can't change it. – prf Sep 03 '13 at 23:13
  • @prf I would suggest Json.NET - it's still my go-to. I *believe* this can be handled with either using a [JsonConvertAttribute](http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializationAttributes.htm) for a custom [de]serializer or a non-serialized property and conditional [partial fragment restoration](http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializationAttributes.htm) (or a combination of both). – user2246674 Sep 03 '13 at 23:14

2 Answers2

0

With Json.Net, you can dynamically process your json

string json1 = @"{""errors"":{""code"":""1"",""description"":""description""}}";
string json2 = @"{""errors"":[{""code"":""1"",""description"":""description""},{""code"":""2"",""description"":""description""}]}";

var obj = JObject.Parse(json1 or json2);

if (obj["errors"] is JArray)
{
    foreach (var error in obj["errors"])
    {
        Console.WriteLine(error["code"].ToString());
    }
}
else
{
    Console.WriteLine(obj["errors"]["code"].ToString());
}
I4V
  • 34,891
  • 6
  • 67
  • 79
-1

I think you can have a look at this answer. You need to deserialize your JSON by using Newtonsoft for example.

If you don't have your classes created you can copy your JSON and click on Paste as JSON.

‘Paste JSON As Classes’ is a cool feature in ASP.NET and Web Tools 2012.2 RC. This feature will help you generate strongly typed classes in C# or VB.NET from valid JSON text.

Community
  • 1
  • 1
glautrou
  • 3,140
  • 2
  • 29
  • 34
  • I'm using VS 2008, not ASP.NET nor Web Tools 2012. I've created my classes by myself and also tried json2csharp, but get the same result. Also, I'm trying to avoid use any third party libs like Json.Net (Newtonsoft) as much as possible, but I'll take a look. – prf Sep 03 '13 at 22:54
  • VS 2008 and ASP.NET are not the same, one is an IDE and the other a technology. You can create an empty ASP.Net project in VS to automatically generate the code for you. I can understand that you try to avoid third parties, but there is no point to write your custom library if free and widely used alternatives exist. Your JSON is quite clean, but if tomorrow you receive many arrays of arrays your code will become quite complicated, and you can quickly have performance issues if your library is not well implemented. – glautrou Sep 04 '13 at 08:26
  • If you still don't want to rely on third party libraries you have a look at how they are implemented. – glautrou Sep 04 '13 at 08:29