2017-09-20 4 views
0

que je prends un DataSet et la convertir en JSON via JSON.NETJSON.NET convertir clé spécifique en nombre entier

La question que je suis face est que l'un des champs est stockée en tant que valeur à virgule flottante, mais J'ai besoin de sérialiser comme un nombre entier à la place. Je ne veux pas changer tous virgule flottante en entier, juste ce champ.

Est-ce que quelqu'un en a un exemple?

+0

Comment convertir un DataSet à JSON? s'il vous plaît partager votre code et quelques exemples de données et votre résultat attendu de ce -HTH;). –

Répondre

0

disons que nous avons rempli les données de dbTable. nous devons changer de son propre type de valeur dbTableField de champ à double:

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

ci-dessous est une classe 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); 
      } 
     } 
    } 

ce lien serait utile: https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm