验证文件后,错误的无效json原语

时间:2019-01-25 06:50:27

标签: c# json

我尝试使用javascriptserializer反序列化json,但收到错误“无效的json原语”

我提到了其他帖子来验证json。

JavaScriptSerializer sr = new JavaScriptSerializer();
dynamic jsonObject = sr.DeserializeObject(@"TableReloadStatus.json");
jsonObject.SchemaName = "Test";
var modifiedJsonString = sr.Serialize(jsonObject);

我的json:

[{
    "Tables":[
    {
        "ServerName": "win-3hog2kbe0g2",
        "TaskName": "tskMovieDemoUAT2",
        "SchemaName": "MOVIEDEMO",
        "TableName": "MOVIE_FACT_HDFS_EXT_TAB",
        "DateReload": "01/25/2019"
    },
    {
        "ServerName": "win-3hog2kbe0g2",
        "TaskName": "tskMovieDemoUAT",
        "SchemaName": "MOVIEDEMO",
        "TableName": "MOVIE_FACT_HDFS_EXT_TAB",
        "DateReload": "01/24/2019"
    }
    ]
}]

1 个答案:

答案 0 :(得分:3)

有一个包含Tables的JSON数组,另一个JSON数组不是对象,因此您可以尝试使用它。

JavaScriptSerializer sr = new JavaScriptSerializer();
dynamic jsonObject = sr.DeserializeObject(@"TableReloadStatus.json");
jsonObject[0].Tables[0].SchemaName = "Test";

我推荐json.net库。

我将使用类模型来携带JSON,而不是使用dynamic

JsonConvert.DeserializeObject<T>

public class Table
{
    public string ServerName { get; set; }
    public string TaskName { get; set; }
    public string SchemaName { get; set; }
    public string TableName { get; set; }
    public string DateReload { get; set; }
}

public class RootObject
{
    public List<Table> Tables { get; set; }
}

然后使用。

string jsonData = File.ReadAllText(@"TableReloadStatus.json");
var jsonObject = JsonConvert.DeserializeObject<List<RootObject>>(jsonData);

c# online