0

I have a C#/ASP.Net project using WebAPI2 that has an API endpoint. That endpoint provides an array of JSON objects as a response to a GET request. I use a Model of the native object for serialisation, which is the standard way in WebAPI2 as I understand it.

The serialization happens 'behind the scenes' when I send an OK HttpActionResult typed for an IEnumerable of models,

 return Ok<IEnumerable<Model>>(arrayOfModels);  

I have a second app that receives the JSON string representation of the array of models. The inbound string to deserialise looks like this, for an array with a single element...

[
  {
    "ExecID": "EXWB4KT-1",
    "Symbol": "CERT-EUR-TEST",
    "ExecutionTime": "2016-07-28T14:59:56.24",
    "BuyExchID": "IDH64KT-1",
    "SellExchID": "IDH64KT-3",
    "Tradable": {
        "CERT": {
            "AccSrc": "ANDY-CERT",
            "AccDst": "HIBLET-CERT",
            "Qty": "0.01000000",
            "State": "PENDING"
        },
        "EUR1": {
            "AccSrc": "HIBLET-EUR",
            "AccDst": "ANDY-EUR",
            "Qty": "0.33",
            "State": "PENDING"
        }
    }
  }
]

How should I rehydrate the JSON data, bearing in mind that I have the WebAPI2 model available in another project?

As I have control of both ends, I am thinking the deserialisation back into an array of models should be trivial, but I am not sure how to do it. I know there are lots of possible ways to do this, I am looking for the sanest or cleanest way.

1 Answer 1

1

Try the Newsoft.Json nuget package. Then it's a matter of creating your model and deserializing. Something like this:

public class MyObject
{ 
    int ExecID { get; set; }
    string Symbol { get; set; }
    //etc etc   
}

Then in your method:

using Newtonsoft.Json;

public class MyMethod(string json)
{
     List<MyObject> objList = JsonConvert.DeserializeObject<List<MyObject>>(json);
}

This code may not be exact, but should be something similar

Sign up to request clarification or add additional context in comments.

1 Comment

Hot diggety, that's exactly what I was hoping for. For others that come this way, the code exactly is 'List<Model> models = JsonConvert.DeserializeObject<List<Model>>(json);'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.