将字符串转换为JSON对象

时间:2019-03-18 13:30:36

标签: c# json string

我使用Microsoft转换器API,并尝试将答案转换为JSON对象以获取检测到的语言。

这是答案字符串

"[{\"language\":\"de\",\"score\":1.0,\"isTranslationSupported\":true,\"isTransliterationSupported\":false,\"alternatives\":[{\"language\":\"nl\",\"score\":1.0,\"isTranslationSupported\":true,\"isTransliterationSupported\":false},{\"language\":\"en\",\"score\":1.0,\"isTranslationSupported\":true,\"isTransliterationSupported\":false}]}]"

我需要第一个“语言”:“ de”

我已经准备尝试使用Newtonsoft JObject.Parse()进行转换,但确实可以正常工作

这是将字符串打印到控制台后的样子:

[{"detectedLanguage":{"language":"de","score":0.8},"translations":[{"text":"Hallo Mein Name ist Danny","to":"de"},{"text":"Ciao il mio nome è Danny","to":"it"}]}]

这就是JObject.Parse(string);

打印的错误
Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.

编辑:

这是JSON字符串来自的HTTPRequest:

   string TranslateText(string text)
{
    string host = "https://api.cognitive.microsofttranslator.com";
    string route = "/translate?api-version=3.0&to=de&to=it";
    string subscriptionKey = COGNITIVE_SERVICES_KEY;

    System.Object[] body = new System.Object[] { new { Text = @text } };
    var requestBody = JsonConvert.SerializeObject(body);

    using (var client = new HttpClient())
    using (var request = new HttpRequestMessage())
    {
        // Set the method to POST
        request.Method = HttpMethod.Post;
        // Construct the full URI
        request.RequestUri = new Uri(host + route);
        // Add the serialized JSON object to your request
        request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
        // Add the authorization header
        request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
        // Send request, get response
        var response = client.SendAsync(request).Result;
        var jsonResponse = response.Content.ReadAsStringAsync().Result;
        // Print the response
        return jsonResponse;
    }
}

然后我尝试使用响应:

string json = TranslateText(text);

JArray jArray = JArray.Parse(json);

string firstLanguage = jArray[0]["language"].ToString();

Response是一个有效的json,因为如果我将响应写到代码中就可以了,但是似乎我需要等到请求响应为其分配结果之后。

3 个答案:

答案 0 :(得分:2)

使用JsonConvert.Deserialize方法反序列化。

由于您尝试反序列化为JObject,因此不会直接反序列化,因为您的JSON字符串包含一个数组,因此先将其转换为List<JObject>,然后执行.FirstOrDefault()来找出language属性的值。

public class Program
{
    public static void Main(string[] args)
    {
        string data = "[{\"language\":\"de\",\"score\":1.0,\"isTranslationSupported\":true,\"isTransliterationSupported\":false,\"alternatives\":[{\"language\":\"nl\",\"score\":1.0,\"isTranslationSupported\":true,\"isTransliterationSupported\":false},{\"language\":\"en\",\"score\":1.0,\"isTranslationSupported\":true,\"isTransliterationSupported\":false}]}]";

        List<JObject> deserializedObject = JsonConvert.DeserializeObject<List<JObject>>(data);

        string languageCode = deserializedObject.FirstOrDefault()["language"]?.ToString() ?? string.Empty;

        Console.WriteLine(languageCode);
    }
}

答案 1 :(得分:1)

尝试这种方式:

string str = "[{\"language\":\"de\",\"score\":1.0,\"isTranslationSupported\":true,\"isTransliterationSupported\":false,\"alternatives\":[{\"language\":\"nl\",\"score\":1.0,\"isTranslationSupported\":true,\"isTransliterationSupported\":false},{\"language\":\"en\",\"score\":1.0,\"isTranslationSupported\":true,\"isTransliterationSupported\":false}]}]";

dynamic arr = JsonConvert.DeserializeObject(str);

string language = arr[0].language;

语言值:

  

“ de”

答案 2 :(得分:1)

您与JObject差不多,

但是您的json不是对象,而是对象的数组,因此您需要JArray才能成功解析它。

1)将其解析为JArray

2)通过查询JArray,您可以使用索引0获得第一语言。

string json = @"[{""detectedLanguage"":{""language"":""de"",""score"":0.8},""translations"":[{""text"":""Hallo Mein Name ist Danny"",""to"":""de""},{""text"":""Ciao il mio nome è Danny"",""to"":""it""}]}]";

JArray jArray = JArray.Parse(json);

string firstLanguage = jArray[0]["detectedLanguage"]["language"].ToString();

输出:(来自调试器)

enter image description here