C# JSON.NET将特定键转换为整数
我正在获取一个C# JSON.NET将特定键转换为整数,c#,json,serialization,json.net,dataset,C#,Json,Serialization,Json.net,Dataset,我正在获取一个数据集,并通过JSON.NET将其转换为JSON 我面临的问题是其中一个字段存储为浮点值,但我需要将其序列化为整数。我不想把所有的浮点数都改成整数,只需要那个字段 有人举过这样的例子吗?假设ds中填充了dbTable中的数据。我们需要将字段dbTableField值类型从其自身更改为double: var ds = new DataSet(); new SqlDataAdapter(com).Fill(ds, "dbTable"); var result = JsonConvert
数据集
,并通过JSON.NET将其转换为JSON
我面临的问题是其中一个字段存储为浮点值,但我需要将其序列化为整数。我不想把所有的浮点数都改成整数,只需要那个字段
有人举过这样的例子吗?假设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);
}
}
}
class DataSetFieldTypeConverter:JsonConverter
{
私有类型转换到;
私有字符串表名;
私有字符串字段名;
公共DataSetFieldTypeConverter(类型convertTo、字符串tableName、字符串fieldName)
{
this.convertTo=convertTo;
this.tableName=tableName;
this.fieldName=字段名;
}
公共重写void WriteJson(JsonWriter编写器、对象值、JsonSerializer序列化器)
{
JToken t=JToken.FromObject(值);
if(t.Type!=JTokenType.Object)
{
t、 书面(作者);
}
其他的
{
JObject jsonObj=t作为JObject;
if(jsonObj!=null&&jsonObj[tableName]!=null&&jsonObj[tableName][0][fieldName]!=null)
{
var propVal=jsonObj[tableName][0][fieldName].Value();
//在这里写下你自己的秘密逻辑
if(convertTo==typeof(int))
{
int-propValInt;
if(内锥虫(propVal,外锥虫))
{
jsonObj[tableName][0][fieldName]=propValInt;
}
}
if(convertTo==typeof(double))
{
双丙戊酸;
if(双倍色氨酸(propVal,out PropValent))
{
jsonObj[tableName][0][fieldName]=propValInt;
}
}
jsonObj.WriteTo(作者);
}
}
}
此链接非常有用:如何将数据集转换为JSON?请共享您的代码和一些示例数据以及您的预期结果(HTH;)。