2017-10-20 18 views
0

我想是这样的检查是否JSON是转换为C#类

public object LoadFromConfig(Type type, string sectionName) 
{ 
    try 
    { 
    serializedJson = //fetch and serialize the Json from given sectionName 
    return JsonConvert.DeserializeObject(serializedJson, type, 
    JsonSerializerSettings); 

    } 
    //was expecting this exception if serializedJson is not convertible to type. 
    catch(ArgumentException e) 
    { 

    return null; 

    } 

DeserializedObject将返回type类型的空对象的情况下,如果serializedJson不是为type匹配。在这种情况下,我想返回null。请提供您的建议。

+0

你是什么意思,*如果'serializedJson'不是'type' *的匹配项?是否有''$ type“'属性指定一个不能分配给'type'的类型?或者''type'和JSON中的实际属性之间没有共同的属性?你可以[编辑]你的问题分享一个具体的[mcve]?默认情况下,[json](http://www.json.org/)对象是** untyped ** - 它们只是一个*无序的名称/值对组*。 Json.NET将按照名称匹配C#和JSON属性,将JSON反序列化为所需的类型。 – dbc

回答

0

@YakRangi,我认为雅各布是给你用的通用型好点,你应该创建一个你期待的JSON相当于符合你的类,然后调用

JsonConvert.DeserializeObject<T>(serializedJson, JsonSerializerSettings); 

现在,让我们说,你期望的JSON有一个属性password这是一个字符串,然后创建类,因为这

class MyClass 
{ 
    [JsonProperty("password")] 
    public string Password 
} 

那么你有一个

try 
{ 
    var res = JsonConvert.DeserializeObject<MyClass>(serializedJson, JsonSerializerSettings); 
} 
catch 
{ 
    return null; 
} 

希望这会有帮助