且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ASP.NET Web API中接收JSON?

更新时间:2023-02-15 17:54:38

在Web API中,您可以让框架为您完成大部分繁琐的序列化工作.首先将您的方法修改为:

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; }
}

此类的属性需要镜像JSON的结构.我将它留给您完成向模型中添加属性和其他类的步骤,但是按照书面形式,该模型应该可以工作.不符合您的模型 的JSON值将被丢弃.

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.

现在,当您调用Web API方法时,传感器数据将已经反序列化.

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

有关更多信息,请参见 http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

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