0

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?

1
  • How do you convert a DataSet to JSON? please share your code and some sample data and your expected result of that -HTH ;). Commented Sep 20, 2017 at 16:29

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.