Gargoyle
Gargoyle

Reputation: 10345

JSON.NET convert specific key to integer

I'm taking a DataSet and converting it to JSON via JSON.NET

The issue I'm facing is that one of the fields is stored as a floating point value but I need it to serialize as an integer instead. I don't want to change all floating point to integer, just that one field.

Does anyone have an example of that?

Upvotes: 0

Views: 1569

Answers (1)

Z.R.T.
Z.R.T.

Reputation: 1603

let say we have ds filled with data from dbTable. we need to change field dbTableField value type from it's own to double:

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

below is a DataSetFieldTypeConverter class:

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);
            }
        }
    }

this link would be useful : https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm

Upvotes: 1

Related Questions