相关疑难解决方法(0)

JSON.net:如何在不使用默认构造函数的情况下反序列化?

我有一个具有默认构造函数的类,也是一个带有一组参数的重载构造函数.这些参数与对象上的字段匹配,并在构造时分配.此时我需要默认构造函数用于其他目的,所以我想保留它,如果可以的话.

我的问题:如果我删除默认构造函数并传入JSON字符串,该对象将正确反序列化并传入构造函数参数而不会出现任何问题.我最终以我期望的方式取回填充的对象.但是,只要我将默认构造函数添加到对象中,当我调用JsonConvert.DeserializeObject<Result>(jsontext)属性时就不再填充了.

此时我尝试添加new JsonSerializerSettings(){CheckAdditionalContent = true}反序列化调用.那什么都没做.

另一个说明.除了参数以小写字母开头之外,构造函数参数确实与字段的名称完全匹配.我不认为这很重要因为,就像我提到的,反序列化工作正常,没有默认构造函数.

这是我的构造函数的示例:

public Result() { }

public Result(int? code, string format, Dictionary<string, string> details = null)
{
    Code = code ?? ERROR_CODE;
    Format = format;

    if (details == null)
        Details = new Dictionary<string, string>();
    else
        Details = details;
}
Run Code Online (Sandbox Code Playgroud)

c# json json.net

117
推荐指数
3
解决办法
9万
查看次数

C#中的JSON反序列化如何工作

我试图了解如何JsonConvert.DeserializeObject<X>(someJsonString)使用构造函数设置值.

using Newtonsoft.json

public class X {

    [JsonProperty("some_Property")]
    public string SomeProperty {get;}

    [JsonProperty("some_Property_2")]
    public string SomeProperty2 {get;}

    public X(string someProperty, string someProperty2) {
        SomeProperty = someProperty;
        SomeProperty2 = someProperty2;
    }

    public static X parseObject(string parseThisJson) {
      JsonConvert.DeserializeObject<X>(someJsonString);
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我想了解JsonConvert.DeserializeObject如何能够正确地反序列化它.json序列化是否使用此public X(string someProperty, string someProperty2)构造函数?如果是这样,如何调用和使用此构造函数?

会发生什么是parseThisJson除了some_Property和some_Property_2之外还有更多的键值对?

c# json.net

10
推荐指数
1
解决办法
2648
查看次数

输入字符串不是有效数字 - JSON 反序列化

我有这个数组:

{
    "AssemblyVersion":"0.1.333.5973",
    "Exception":
    {
        // [...]
    }
}
Run Code Online (Sandbox Code Playgroud)

它是从此类序列化的:

public class ErrorData
{
    public string AssemblyVersion { get; private set; }
    public Exception Exception { get; private set; }

    public ErrorData(string assemblyVersion, Exception ex)
    {
        AssemblyVersion = assemblyVersion;
        Exception = ex;
    }

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

将其序列化回对象会产生以下异常:

Newtonsoft.Json.JsonReaderException: Input string '0.1.335.5973' is not a valid number. Path 'AssemblyVersion', line 1, position 29.
    at Newtonsoft.Json.JsonTextReader.ParseNumber(ReadType readType)
    at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
    at Newtonsoft.Json.JsonTextReader.ReadAsString()
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract …
Run Code Online (Sandbox Code Playgroud)

c# json.net

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×3

json.net ×3

json ×1