解析值JSON对象时遇到意外的字符

时间:2016-08-14 22:21:54

标签: c# xamarin xamarin.forms xamarin-studio

我有一个看起来像这样的JSON对象:

"field2_body":null,"field3_body":null,"field4_body":null,"h_phrases":[{"h_phrase":"H222"},{"h_phrase":"H411"},{"h_phrase":"H361"},{"h_phrase":"H315"}]

但这只是JSON对象的一部分,因为它非常大。

我想要做的是访问h_phrase字符串值但是当我尝试时出现此错误:

  

错误解析值时遇到意外的字符:{。路径'[0] .h_phrases',第64行,第7位。

这是我的代码:

public class PhrasesData
{ 
    [JsonProperty(PropertyName = "h_phrases")]
    public string H_Phrases { get; set; }
}

public async void getPhrasesForSpecificProduct(string productId)
{
    var baseUrl = "http://www.kemtest.com/rest/organisations";
    var specProductUrl = baseUrl + "/" + activeOrganisationId + "/" + "products/" + productId;

    try
    {

        var baseAddress = new Uri(specProductUrl);
        var cookieContainer = new CookieContainer();
        using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
        using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
        {

            validToken = System.Net.WebUtility.UrlEncode(validToken);
            cookieContainer.Add(baseAddress, new Cookie("access_token", string.Format(validToken)));
            var result = client.GetAsync(specProductUrl).Result;

            result.EnsureSuccessStatusCode();

            if (result.IsSuccessStatusCode)
            { 
                var content = await result.Content.ReadAsStringAsync();
                var array = JArray.Parse(content);

                PhrasesData[] myPhrasesData = JsonConvert.DeserializeObject<PhrasesData[]>(array.ToString());

                if (myPhrasesData == null)
                    throw new JsonException();
                string[] H_PhrasesArr = new string[myPhrasesData.Length];
                for (int i = 0; i < myPhrasesData.Length; i++)
                {
                    H_PhrasesArr[i] = myPhrasesData[i].H_Phrases;
                    var H_PhrasesVar = H_PhrasesArr[i];
                    Debug.WriteLine("God Damn PHRASES: " + H_PhrasesVar);
                }

            }
        }
    }catch (Exception ex) { Debug.WriteLine(@"              ERROR {0}", ex.Message); }
}

我的代码有什么问题?

1 个答案:

答案 0 :(得分:2)

您的JSON字符串无效。你需要用{和}括起来。

在使用JSON对象编码之前使用http://jsonlint.com/

{

    "field2_body": null,
    "field3_body": null,
    "field4_body": null,
    "h_phrases": [{
        "h_phrase": "H222"
    }, {
        "h_phrase": "H411"
    }, {
        "h_phrase": "H361"
    }, {
        "h_phrase": "H315"
    }]

}