7

I have an external company pushing data to one of our server, they are going to send JSON data. I need to create a POST api to receive it. This is what I have so far

[System.Web.Http.HttpPost]
[System.Web.Http.ActionName("sensor")]
public void PushSensorData(String json)
{
    string lines = null;
    try
    {
          System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
          file.WriteLine(json);
          file.Close();
          //JSONUtilities.deserialize(json);
    }
    catch (Exception ex)
    {
        MobileUtilities.DoLog(ex.StackTrace);
    }
}

I am testing it by send json data using fiddler but json is null. This is the raw data from fiddler.

POST http://localhost:31329/mobileapi/pushsensordata/ HTTP/1.1
User-Agent: Fiddler
Host: localhost:31329
Content-Type: application/json
Content-Length: 533

{
"id": {
    "server": "0.test-server.mobi",
    "application": "test-server.mobi",
    "message": "00007-000e-4a00b-82000-0000000",
    "asset": "asset-0000",
    "device": "device-0000"
},
"target": {
    "application": "com.mobi"
},
"type": "STATUS",
"timestamp": {
    "asset": 0000000
    "device": 00000000,
    "gateway": 000000,
    "axon_received_at": 00000,
    "wits_processed_at": 000000
},
"data_format": "asset",
"data": "asset unavailable"
}
null
  • 713
  • 2
  • 8
  • 30
  • You decorated your method with `HttpGet`, but want a POST? –  Dec 02 '15 at 17:52
  • My bad, was trying to do something with GET since I wasn't able to get post working. – null Dec 02 '15 at 17:55
  • This is not a string in your request, it's an object. web-api know how to serialize your object to c# object, just try to create one and put is as your parameter. – Avi Dec 02 '15 at 17:59
  • Duplicate question of: http://stackoverflow.com/questions/33895572/how-to-read-json-object-to-webapi/33897842#33897842 – Dietz Dec 02 '15 at 18:43

3 Answers3

13

In Web API you let the framework do most of the tedious serialization work for you. First amend your method to this:

[HttpPost]
public void PushSensorData(SensorData data)
{
    // data and its properties should be populated, ready for processing
    // its unnecessary to deserialize the string yourself.
    // assuming data isn't null, you can access the data by dereferencing properties:
    Debug.WriteLine(data.Type);
    Debug.WriteLine(data.Id);
}

Create a class. To get you started:

public class SensorData 
{
    public SensorDataId Id { get; set; }
    public string Type { get;set; }
}

public class SensorDataId
{
    public string Server { get; set; }
}

The properties of this class need to mirror the structure of your JSON. I leave it to you to finish adding properties and other classes to your model, but as written this model should work. The JSON values that don't correspond to your model should be thrown out.

Now, when you call your Web API method, your sensor data will already be deserialized.

For more information, see http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

  • Note, I removed the `[ActionName]` attribute. It doesn't do much of anything for you. See http://stackoverflow.com/a/6536789/47589 for more information. –  Dec 02 '15 at 18:22
  • So I created the SensorData class. How do I access the data inside the api method? Do I need to do this SensorReading sr = new SensorReading(); and access it using getters – null Dec 02 '15 at 18:49
  • The `data` parameter should be a `SensorData` object. You can access the data by dereferencing its properties. I'll update my answer a bit to help illustrate this. –  Dec 02 '15 at 18:52
  • I would like to encourage you to try this out with a simple model and corresponding simple JSON. Get used to how Web API works, then expand your model in complexity. –  Dec 02 '15 at 18:57
  • Is there a way to get the value inside data even if the field name temperature changes "data": { "temperature": "37C" } – null Dec 02 '15 at 19:24
  • I don't understand what you mean. Please create a new question with a little more detail. –  Dec 02 '15 at 19:33
  • I figured everything out but some of the values might be or might not be there in the json, how would I handle this – null Dec 03 '15 at 19:52
  • Ask in a separate question. –  Dec 03 '15 at 19:53
3

Your Web API model needs to be same as javascript request object

For example,

public class SomeRequest
    {

        public string data1{ get; set; }
        public string data2{ get; set; }
        public string data13{ get; set; }

    }

In Javascript , your request object and javascript call should be like this

 var requestObj = {
                "data1": data1,
                "data2": data2,
                "data3": data3,

            };

And post url and requestObj in javascript

Access in Web API like this

  public void PushSensorData(SomeRequest objectRequest)
        {
objectRequest.data1
objectRequest.data2
objectRequest.data3
Rama Krshna Ila
  • 486
  • 3
  • 11
-2

Have you tried JSON.stringify(yourObject) (this is Javascript but any language has this kind of utility) before passing it to your web api?

May I also point out your comment earlier, stating you're using a GET method because you can't get POST working? You should be careful in your planning because a GET method can only take so much space: if your object becomes larger you'll be forced to use a POST, so I'd suggest you take this approach right away.

hbulens
  • 1,872
  • 3
  • 24
  • 45
  • I am trying to use fiddler to test the program since I have no clue what the other company is using. I am passing json in the request body. – null Dec 02 '15 at 18:08
  • Have you tried something else than JSON, like a simple string? If that works, try passing your JSON as a simple string rather than a JSON object. You accept a string in your web api, it's quite normal you don't get results here. As a test, you could change your data type from string to dynamic, see what happens then. – hbulens Dec 02 '15 at 18:12
  • `JSON.stringify` is irrelevant as the JSON @hbulens is receiving is already well-formed JSON. –  Dec 02 '15 at 18:24
  • I don't think you read my answer all the way through. ASP.NET Web API is particulary sensitive when it comes to correctly formatted parameters. I've had this problem multiple times and stringifying json objects works pretty much every time – hbulens Dec 02 '15 at 20:17