JSON.NET转换特定关键整数
问题描述:
我正在DataSet
并通过JSON.NETJSON.NET转换特定关键整数
我面临的问题是其中一个字段存储为一个浮点值,将其转换为JSON,但我需要它作为一个整数序列化。我不想改变全部浮点数为整数,只是那一个字段。
有没有人有这样的例子?
答
假设我们已经从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
怎样把一个DataSet到JSON?请分享您的代码和一些示例数据以及您希望得到的-HTH;)的结果。 –