Search code examples
c#arraysdefinitionjsonconvert

JsonConvert.DeserializeAnonymousType definition syntax issue


I have the following code:

var definition = new { result = "", accountinformation = new[] { "" ,  "" , "" } };

var accountInformationResult = JsonConvert.DeserializeAnonymousType(responseBody, definition);

The account information structure comes back from an endpoint as an array with each element being another array containing 3 strings. So the embedded array is not in a key value pair format. With the above definition accountinformation returns null. What should the syntax be for this structure?

For reference this is what is going on in the php endpoint.

$account_information[] = array( $billing_company, $customer_account_number, $customer_account_manager );

This first line is in a loop. Hence the multi-dimensional array.

echo json_encode(array('result'=>$result, 'account_information'=>$account_information));

I know I could use dynamic but why the extra effort?


Solution

  • I assume your json will look something like this:

    {
      "result": "the result",
      "account_information": [
        ["company1", "account_number1", "account_manager1"],
        ["company2", "account_number2", "account_manager2"]
      ]
    }
    

    In that case you should be able to deserialize with the following definition (note the underscore in account_information:

    var definition = new { result = "", account_information = new List<string[]>() };
    

    In json you are allowed to add extra properties as you please while your data model changes. So if you define a data model that does not include one of these properties, the property will simple be ignored. In your case the definition does not have a property called account_information (exactly), so this part of the json is ignored while deserializing.

    EDIT: If it's going to be an anonymous abject anyway, you may also consider parsing into a JObject:

    var obj = JObject.Parse(responseBody);
    string firstCompany = obj["account_information"][0][0];
    string secondCompany = obj["account_information"][1][0];