在json中更改对象元素

时间:2018-09-28 10:41:10

标签: c# .net json json.net

我有这样的JSON

{
    "amounts": [
        {
            "tid": 7072,
            "amount": 10000,
            "currency": "USD"
        },
        {
            "tid": 7072,
            "amount": 4000,
            "currency": "USD"
        }
    ],
    "status": 0,
    "errorCode": 0
}

我需要从此JSON检索金额值并将其划分为10。之后,我想替换原始json中的金额值。我怎样才能做到这一点?我正在使用像NEwtonsoft json这样的.Net json工具。

3 个答案:

答案 0 :(得分:1)

private string DivideAmounts(string str, int denominator)
    {
        var obj = (JObject)JsonConvert.DeserializeObject(str);
        foreach (var amount in obj["amounts"])
        {
            var value = amount.Value<int>("amount");
            var newValue = value / denominator;
            amount["amount"] = newValue;
        }
        return obj.ToString();
    }

使用Newtonsoft.Json。 添加参数“分母”的检查以避免被零除错误。

答案 1 :(得分:0)

使用以下tool生成类:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp11
{
    class Program
    {
        static void Main(string[] args)
        {
            var js = "{\"amounts\": [ { \"tid\": 7072, \"amount\": 10000, \"currency\": \"USD\"        },        {            \"tid\": 7072,            \"amount\": 4000,            \"currency\": \"USD\"        }    ],    \"status\": 0,    \"errorCode\": 0}";
            var obj = Welcome.FromJson(js);
            for (int i = 0; i < obj.Amounts.Length; i++)
            {
                obj.Amounts[i].AmountAmount /= 10;
            }
            var newjs = Serialize.ToJson(obj);
            Console.WriteLine(newjs);
            Console.ReadKey();

        }
    }

    public partial class Welcome
    {
        [JsonProperty("amounts")]
        public Amount[] Amounts { get; set; }

        [JsonProperty("status")]
        public long Status { get; set; }

        [JsonProperty("errorCode")]
        public long ErrorCode { get; set; }
    }

    public partial class Amount
    {
        [JsonProperty("tid")]
        public long Tid { get; set; }

        [JsonProperty("amount")]
        public long AmountAmount { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }
    }

    public partial class Welcome
    {
        public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
    }



    public static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters = {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }

    public static class Serialize
    {
        public static string ToJson(this Welcome self)
        {
            return JsonConvert.SerializeObject(self, Converter.Settings);
        }
    }

}

答案 2 :(得分:0)

json2csharp生成快捷类型,如

public class Amount
{
    public int tid { get; set; }
    public int amount { get; set; }
    public string currency { get; set; }
}

public class RootObject
{
    public List<Amount> amounts { get; set; }
    public int status { get; set; }
    public int errorCode { get; set; }
}

1)首先将json string反序列化为RootObject

2)遍历amounts中的RootObject属性。

3)对您的金额进行算术运算,例如除以10。

4)再次序列化您的RootObject

在这里,我为您的演示目的创建了一个控制台应用程序,其中显示了如何执行上述步骤。

class Program
{
    static void Main(string[] args)
    {
        string inputJson = @"{'amounts':[{'tid':7072,'amount':10000,'currency':'USD'},{'tid':7072,'amount':4000,'currency':'USD'}],'status':0,'errorCode':0}";

        RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(inputJson);

        foreach (var item in rootObject.amounts)
        {
            item.amount = item.amount / 10;
        }

        //OR you can do it with shorter version of foreach
        //rootObject.amounts.ForEach(x => x.amount = x.amount / 10);

        string outputJson = JsonConvert.SerializeObject(rootObject);

        Console.WriteLine(outputJson);
        Console.ReadLine();
    }
}

输出:

enter image description here