1 / 1
使用原生程式解析JSON
`
var json = @"{ ""Lat"":""123.456"", ""Other"":"" blah blah blah "" }";
var p = JsonSerializer.Deserialize<Person>(json);
‵
不能正常解析,但是使用
`
var json = @"{ ""Lat"":""123.456"" }";
var p = JsonConvert.DeserializeObject<Person>(json);
Console.WriteLine("Name is: \"{0}\"", p.Name);
public class Person
{
	public float Lat{ get; set; }
	public string Other { get; set; }
}
`
就能把字串解析成float,原生語法我需要怎麼調整?才能順利轉成float?
1 / 1
在使用 System.Text.Json 库进行 JSON 解析时,需要将 Lat 属性声明为 float 类型而不是 string 类型,否则会导致解析失败。以下是使用 System.Text.Json 库进行 JSON 解析的代码示例:
csharpusing System;
using System.Text.Json;
public class Program
{
    public static void Main()
    {
        var json = @"{ ""Lat"":""123.456"" }";
        var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
        var p = JsonSerializer.Deserialize<Person>(json, options);
        Console.WriteLine("Lat is: \"{0}\"", p.Lat);
    }
}
public class Person
{
    public float Lat { get; set; }
    public string Other { get; set; }
}
在上述代码中,我们在 JsonSerializerOptions 对象中将 PropertyNameCaseInsensitive 属性设置为 true,以便在解析 JSON 时不区分属性名的大小写。此外,我们将 Lat 属性声明为 float 类型,以便在解析 JSON 时可以正确转换为浮点数。
2 / 2
得到`The JSON value could not be converted to System.Nullable`1[System.Single]. Path: $.Lat | LineNumber: 0 | BytePositionInLine: 17.`錯誤
1 / 1
这个错误信息表明在将 JSON 字符串转换为 float? 类型(Nullable<float>)时出现了问题,可能是因为 JSON 字符串中的 "Lat" 值无法正确转换为浮点数。
在使用 System.Text.Json 库进行 JSON 解析时,需要注意以下几点:
- System.Text.Json默认不支持将字符串转换为可空类型(如- float?),需要使用- JsonConverter手动实现转换逻辑。
- System.Text.Json的默认序列化/反序列化选项可能与- Newtonsoft.Json不同,例如默认情况下- System.Text.Json不区分属性名的大小写,而- Newtonsoft.Json则区分。
以下是将 float? 类型属性正确反序列化的示例代码:
csharpusing System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class Program
{
    public static void Main()
    {
        var json = @"{ ""Lat"":""123.456"" }";
        var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
        options.Converters.Add(new FloatNullableConverter());
        var p = JsonSerializer.Deserialize<Person>(json, options);
        Console.WriteLine("Lat is: \"{0}\"", p.Lat);
    }
}
public class Person
{
    [JsonPropertyName("Lat")]
    public float? Lat { get; set; }
    public string Other { get; set; }
}
public class FloatNullableConverter : JsonConverter<float?>
{
    public override float? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.Null)
        {
            return null;
        }
        if (reader.TryGetSingle(out float value))
        {
            return value;
        }
        throw new JsonException($"Cannot convert {reader.GetString()} to {typeof(float)}.");
    }
    public override void Write(Utf8JsonWriter writer, float? value, JsonSerializerOptions options)
    {
        if (value.HasValue)
        {
            writer.WriteNumberValue(value.Value);
        }
        else
        {
            writer.WriteNullValue();
        }
    }
}
在上述代码中,我们定义了一个自定义的 JsonConverter 类型 FloatNullableConverter,并将其添加到了 JsonSerializerOptions 中。在 FloatNullableConverter 中,我们手动实现了 float? 类型的反序列化逻辑,以便正确处理可能存在的 null 值。在 Person 类中,我们使用 JsonPropertyName 特性指定了 JSON 中的属性名为 "Lat",以便在反序列化时正确匹配。