.net 如何从收到的请求正文中删除字符

hlswsv35  于 2023-02-10  发布在  .NET
关注(0)|答案(1)|浏览(137)

我试图开发一个API来接收来自IOT设备的GPS数据。下面是来自设备的数据。

O||GPS[ {"GPSTime": "01/09/2021 02:34:03", "Coordinates": "0.000000", "RegisterNo": "144"} ]

我已经创建了一个API如下所述。当我发布数据到这个API它给出了错误的请求,因为无效的JSON格式。需要知道如何从接收到的请求体中删除字符,以及如何只从花括号内的数据。

public class GPSController : ApiController
    {
   [HttpPost]
        [Route("GPSData")]
        // public HttpResponseMessage Post([FromBody]GPSModel gPSData)

        public HttpResponseMessage Post([FromBody]GPSData gPSData)
        {
            using (DBEntities entities = new DBEntities())
                {

                      var ins = new GPSData();

                        
                        ins.Coordinates= gPSData.Coordinates;
                        ins.GPSTime = gPSData.GPSTime;
                        ins.UpdatedTime = DateTime.Now;
                        entities.GPSDatas.Add(ins);
                        entities.SaveChanges();

          
                    var message = Request.CreateResponse(HttpStatusCode.Created, gPSData);
                    message.Headers.Location = new Uri(Request.RequestUri + gPSData.RegisterNo.ToString());
                    return message;

                  }

            }

}
tjvv9vkg

tjvv9vkg1#

要从接收到的请求正文中删除字符并仅从花括号内获取数据,可以执行以下操作:
1.将请求主体解析为字符串,并使用字符串操作方法(如Substring和IndexOf)提取花括号之间的数据。
1.使用JSON库(如Newtonsoft.JSON)将提取的字符串反序列化到GPSData模型中。
使用以下代码:

public HttpResponseMessage Post(){ 
         // Parse the request body as a string
var body = Request.Content.ReadAsStringAsync().Result;
// Extract the data between the curly brackets
var startIndex = body.IndexOf("{");
var endIndex = body.IndexOf("}") + 1;
var gpsDataJson = body.Substring(startIndex, endIndex - startIndex);
// Deserialize the extracted string into your GPSData model
GPSData gpsData = JsonConvert.DeserializeObject<GPSData>(gpsDataJson);

using (DBEntities entities = new DBEntities())
{
    var ins = new GPSData();
    ins.Coordinates = gpsData.Coordinates;
    ins.GPSTime = gpsData.GPSTime;
    ins.UpdatedTime = DateTime.Now;
    entities.GPSDatas.Add(ins);
    entities.SaveChanges();

    var message = Request.CreateResponse(HttpStatusCode.Created, gpsData);
    message.Headers.Location = new Uri(Request.RequestUri + gpsData.RegisterNo.ToString());
    return message;
}
}

相关问题