[英]Get values from JSON result C#
我正在嘗試通過使用Azure讀取圖像上的文本來從計算機視覺api結果中獲取值。 輸出為JSON數據,但結果的語法看起來很奇怪。
最終,我試圖從中剝離出“文本”值,並將其寫入文本文件,而沒有任何轉義字符等。
這是我正在使用解析結果的代碼。
static async Task MakeOCRRequest(string imageFilePath)
{
try
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
string requestParameters = "language=unk&detectOrientation=true";
string uri = uriBase + "?" + requestParameters;
HttpResponseMessage response;
byte[] byteData = GetImageAsByteArray(imageFilePath);
using (ByteArrayContent content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uri, content);
}
string contentString = await response.Content.ReadAsStringAsync();
/////// It is at this point that I want to get the values from the "text" field
JToken token = JToken.Parse(contentString).ToString();
String[] result = contentString.Split(',');
Console.writeline("\nResponse:\n\n{}\n", JToken.Parse(contentString).ToString());
}
catch (Exception e)
{
Console.WriteLine("\n" + e.Message);
}
}
這是我從OCR流程中得到的結果。 我沒有包括完整的結果,因為它代表了1700多行。
"language": "en",
"textAngle": 0.0,
"orientation": "Right",
"regions": [
{
"boundingBox": "140,300,639,420",
"lines": [
{
"boundingBox": "419,300,87,15",
"words": [
{
"boundingBox": "419,300,87,15",
"text": "0000175351"
}
]
},
{
"boundingBox": "140,342,337,47",
"words": [
{
"boundingBox": "140,347,92,38",
"text": "WE."
},
{
"boundingBox": "241,347,13,36",
"text": "1"
},
{
"boundingBox": "266,342,211,47",
"text": "0/1-1.9(2)"
}
]
},
使用當前代碼,我收到錯誤消息
JObject textResult = token["regions"]["text"].Value<JObject>();
無法訪問
NewtonSoft.Json.Linq.JValue
上的子值。
我想知道我是否要求輸入錯誤的鑰匙?
假設您現在擁有一個有效的JSON字符串,則可以使用Newtonsoft.Json
包並將json字符串反序列化為object,然后使用object獲取值:
ResponseModel res = JsonConvert.DeserializeObject<ResponseModel>(contentString);
您的響應模型可能是像這樣的pocco類:
public class ResponseModel
{
public string language { get; set; }
public string textAngle { get; set; }
public string orientation { get; set; }
//you have to create pocco class for RegionModel
public List<RegionModel> regions { get; set; }
....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.