【问题标题】:JSON.NET convert specific key to integerJSON.NET 将特定键转换为整数
【发布时间】:2017-09-20 15:46:26
【问题描述】:

我正在使用 DataSet 并通过 JSON.NET 将其转换为 JSON

我面临的问题是其中一个字段存储为浮点值,但我需要将其序列化为整数。我不想将 all 浮点数更改为整数,只是一个字段。

谁有这方面的例子?

【问题讨论】:

  • 如何将数据集转换为 JSON?请分享您的代码和一些示例数据以及您对该 -HTH 的预期结果;)。

标签: c# json serialization json.net dataset


【解决方案1】:

假设我们的 ds 中填充了来自 dbTable 的数据。我们需要将字段 dbTableField 的值类型从它自己的类型更改为 double:

var ds = new DataSet();
new SqlDataAdapter(com).Fill(ds, "dbTable");
var result = JsonConvert.SerializeObject(ds, Formatting.Indented, new 
DataSetFieldTypeConverter(typeof(double), "dbTable", "dbTableField"));

下面是一个DataSetFieldTypeConverter类:

class DataSetFieldTypeConverter : JsonConverter
{
    private Type convertTo;
    private string tableName;
    private string fieldName;
    public DataSetFieldTypeConverter(Type convertTo, string tableName, string fieldName)
    {
        this.convertTo = convertTo;
        this.tableName = tableName;
        this.fieldName = fieldName;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JToken t = JToken.FromObject(value);

        if (t.Type != JTokenType.Object)
        {
            t.WriteTo(writer);
        }
        else
        {
            JObject jsonObj = t as JObject;
            if (jsonObj != null && jsonObj[tableName] != null && jsonObj[tableName][0][fieldName] != null)
            {
                var propVal= jsonObj[tableName][0][fieldName].Value<string>();

                //Write your own covert logic here

                if (convertTo == typeof(int))
                {
                    int propValInt;
                    if (int.TryParse(propVal, out propValInt))
                    {
                        jsonObj[tableName][0][fieldName] = propValInt;
                    }
                }
                if (convertTo == typeof(double))
                {
                    double propValInt;
                    if (double.TryParse(propVal, out propValInt))
                    {
                        jsonObj[tableName][0][fieldName] = propValInt;
                    }
                }
                jsonObj.WriteTo(writer);
            }
        }
    }

这个链接会很有用:https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2021-02-06
    相关资源
    最近更新 更多