Json对象解析错误

时间:2016-08-25 16:33:48

标签: c# json cassandra

我将数据存储在我的cassandra数据库中作为字符串,我想检索字符串并将其转换为json。我得到一个例外

类型' Newtonsoft.Json.JsonReaderException'未处理的异常发生

存储的数据有问题吗?或者我在做其他一些错事?

我的查询是:

INSERT INTO table2(key1,col1) values ('5',{'url':'{"hello":
    {"hi":{"hey":"1","time":"5"}},
    {"reg":{"hey":"1","time":"1"}},
    {"install":{"hey":"0"}}},
    "task":"1","retry":"00",
    "max":"5","call":"140"'});


In my db when i click the map<text,text> column, it gets stored as : 

 {\"hello\":\r\n    
    {\"subscription_atrisk\":{\"hey\":\"1\",\"time\":\"100\"}},
    {\"reg\":{\"hey\":\"1\",\"time\":\"2000\"}},
\"task\":\"0\",\"retry\":\"300\",\"max\":\"5\",\"call\":\"14400\"}

在我的c#代码中,我尝试

string s = "{\"hello\":\r\n    {\"subscription_atrisk\":{\"hey\":\"1\",\"time\":\"100\"}},{\"reg\":{\"hey\":\"1\",\"time\":\"2000\"}},\"task\":\"0\",\"retry\":\"300\",\"max\":\"5\",\"call\":\"14400\"";
Jobject json = Jobject.Parse(s); //Get an Error here.

有人可以对此有所了解吗?

2 个答案:

答案 0 :(得分:1)

您似乎错过了结束} 尝试:

string s = "{\"hello\": {\"subscription_atrisk\":{\"hey\":\"1\",\"time\":\"100\"}}, \"missing_key\": {\"reg\":{\"hey\":\"1\",\"time\":\"2000\"}},\"task\":\"0\",\"retry\":\"300\",\"max\":\"5\",\"call\":\"14400\"}";

答案 1 :(得分:1)

在JSON中,对象应包含键和或其他对象/数组。 您的JSON对象中存在语法错误。首先,始终使用双引号。

然后...... url对象有一个键Hello,但是在那里你应该再放两个键,你只需要再放两个对象,好像它是一个数组

这可能是正确的语法:

{
"url": {
    "hello": {
        "hi": {
            "hey": "1",
            "time": "5"
        }
    },
    "MissingKey1":{
        "reg": {
            "hey": "1",
            "time": "1"
        }
    },
    "MissingKey2":{
        "install": {
            "hey": "0"
        }
    }
},
"task": "1",
"retry": "00",
"max": "5",
"call": "140"
}

或者,如果您真的打算在hello内有一个url对象和另外两个对象的数组:

{
"url": {
    "hello": {
        "hi": {
            "hey": "1",
            "time": "5"
        }
    },
    "AnArray": [{
        "reg": {
            "hey": "1",
            "time": "1"
        }
    }, {
        "install": {
            "hey": "0"
        }
    }]
},
"task": "1",
"retry": "00",
"max": "5",
"call": "140"

}

我建议在将这些JSON对象存储到数据库之前,总是验证它们以确保它们的语法有效。

甚至更好:这个Newtonsoft库提供了从其他对象序列化(创建)JSON字符串的函数。见JsonConvert.SerializeObject Method

一般来说,查看API文档是个好主意,它可以为您节省大量时间,这样您就不必进行不必要的工作。

相关问题