当前的JsonReader项不是对象

时间:2016-11-24 15:38:35

标签: c# json unit-testing parsing json.net

首先我做了一个应用程序,然后我开始为它做测试(知道这不是好方法),一切正常,解析等,但在我做了几个测试后得到了一个错误:

  

Newtonsoft.Json.JsonReaderException:从JsonReader读取JObject时出错。当前的JsonReader项不是对象:StartArray。路径'',第1行,第1位。

jObject = JObject.Parse(content);arrayList = JArray.Parse(content);

出现错误
internal JObject DoParse(string content)
{
    JObject jObject = new JObject();
    if (content != null)
    {
        if (content.Contains("Unable"))
        {
            MessageBox.Show("Not found.", "Error");
        }
        else
        {
            jObject = JObject.Parse(content);
        }
    }
    return jObject;
}

internal JArray DoParseOnList(string content)
{
    JArray arrayList = new JArray();
    if (content != null)
    {
        if (content.Contains("Unable"))
        {
            MessageBox.Show("Not found.", "Error");
        }
        else
        {

            arrayList = JArray.Parse(content);
        }
    }
    else { }
    return arrayList;
}

任何想法有什么不对? 顺便说一句。 string content是我从服务器获得的json。 提前谢谢!

JSON

Test Name:  SetGroup
Test Outcome:   Failed
Result Message: SetUp : Newtonsoft.Json.JsonReaderException : Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Result StandardOutput:  [{"id":6208,"name":"test"},{"id":6315,"name":"jPOD v144 Testing"},{"id":6306,"name":"iButton Issue"},{"id":6424,"name":"Hybrid"}]
[{"id":6208,"name":"test"},{"id":6315,"name":"jPOD v144 Testing"},{"id":6306,"name":"iButton Issue"},{"id":6424,"name":"Hybrid"}]
[{"enabled":true,"scriptVersion":199,"configVersion":3,"name":"LMU3030 Hybrid Car Test based on 64.112 add ignition on-off"},{"enabled":true,"scriptVersion":199,"configVersion":2,"name":"LMU3030 Hybrid Car Test based on 50.106"},{"enabled":true,"scriptVersion":199,"configVersion":1,"name":"Hybrid car LMU 3030 Ignition test","description":""},{"enabled":true,"scriptVersion":64,"configVersion":113,"name":"based on 64.112 Engineering Build from calamp"},{"enabled":true,"scriptVersion":61,"configVersion":106},{"enabled":true,"scriptVersion":38,"configVersion":117},{"enabled":true,"scriptVersion":184,"configVersion":0},{"enabled":true,"scriptVersion":13,"configVersion":54},{"enabled":true,"scriptVersion":23,"configVersion":105,"name":"PULS Redirect to PROD","description":"Changes just Param 2320 to maint.vehicle-location.com"}]
[]
[{"message":"Not Implemented","vbusDeviceFiles":[],"vbusFileHistories":[]}]

2 个答案:

答案 0 :(得分:5)

我有类似的问题。
返回的JSON是数组/列表,但不是对象。
相反,我使用JArray.Parse,它可以工作。

jArray = JArray.Parse(content);

答案 1 :(得分:2)

我遇到了一个非常类似的问题。我的JObject.Parse(json)不适合我的原因是因为我的Json有一个开始" ["和结束"]"。为了使它工作,我不得不删除这两个字符。我会检查你的Json并确保它以{以#结尾}开头。

对我来说,我删除了第一个和最后一个字符。

jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });