从字符串中解析特定值的最佳方法

问题描述 投票:0回答:1

我想从下面的字符串中解析出浮点数据S值0.2254。最好的方法是什么?

"content": "{\"data S, T, BV\": \"[0.2254],[63.290913252460534],[0.0]\"}"

我正在尝试用 JSON 解析它?我可以获取键和值字段,但不知道该如何处理。

我尝试过这种方法:

var sensorData = await GetDataAsync();
var sensorDataArray = JArray.Parse(sensorData);
foreach (JObject obj in sensorDataArray)
   foreach (KeyValuePair<String, JToken> field in obj)
      if (field.Key == "content")
      {
        //Now I want to parse the contents of field.Value 
        //field.Value contains:  data S, T, BV: "[0.2254],[63.290913252460534],[0.0]"
      }

我不知道从字段中提取 0.2554 的最佳方法。值内容。

c# json parsing
1个回答
0
投票

您似乎在 JSON 的字符串值中转义了 JSON。这意味着您需要解析它两次。

你有这个输入 JSON

{
  "content": "{\"data S, T, BV\": \"[0.2254],[63.290913252460534],[0.0]\"}",
  "contentType": "application/octet-stream",
  "time": 1707417501679
}
var sensorData = "{ \"content\": \"{\\\"data S, T, BV\\\": \\\"[0.2254],[63.290913252460534],[0.0]\\\"}\", \"contentType\": \"application/octet-stream\", \"time\": 1707417501679 }";

// step 1, get the value of the "content" property
var contentPropertyValue = JObject.Parse(sensorData)["content"].Value<string>();

// step 2, reparse the value as JSON
var parsedContentValue = JObject.Parse(contentPropertyValue);

// step 3, get the value of the "data S, T, BV" property
var dataPropertyValue = parsedContentValue["data S, T, BV"].Value<string>();
// dataPropertyValue is now "[0.2254],[63.290913252460534],[0.0]" as a string

// step 4, split by commas, get the first element, remove braces, and parse as double
var finalValue = double.Parse(
    dataPropertyValue
    .Split(',')
    [0]
    .Replace("[", "")
    .Replace("]", ""));
// finalValue is 0.2254 as a double

此代码有许多可空性警告。根据您的场景需要添加空检查。

© www.soinside.com 2019 - 2024. All rights reserved.