Json对象解析错误

本文关键字:错误 对象 Json | 更新日期: 2023-09-27 18:04:04

我将数据存储在我的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.

有人能解释一下吗?

Json对象解析错误

在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"
}

或者如果你真的想在url中有一个hello对象和一个包含两个以上对象的数组:

{
"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方法

一般来说,看看API文档是个好主意,它真的可以节省你很多时间,这样你就不必做不必要的工作了。

看起来你错过了一个关闭}试一试:

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