使用C#中的模型对象更新JSON文件

时间:2016-07-27 13:57:13

标签: c# json

我有一个类似于:

的json文件
[
  {
    "picklist_typ": "Address Assessment Code",
    "picklist_typ_key": null,
    "picklist_typ_cd": "DELIVERABLE",
    "picklist_typ_dsc": "Address is deliverable : Deliverable",
    "ref_order": null,
    "dw_trans_ts": "2016-07-17T12:59:15"
  },
  {
    "picklist_typ": "Address Assessment Code",
    "picklist_typ_key": null,
    "picklist_typ_cd": "NOT-DELIVERABLE",
    "picklist_typ_dsc": "Address is not deliverable : Undeliverable",
    "ref_order": null,
    "dw_trans_ts": "2016-07-17T12:59:15"
  },
  {
    "picklist_typ": "Address Type",
    "picklist_typ_key": null,
    "picklist_typ_cd": "B",
    "picklist_typ_dsc": "Billing Address",
    "ref_order": null,
    "dw_trans_ts": "2016-07-17T12:59:15"
  },
  ....

现在,我有一个看起来像的对象:

public class GroupMembershipWriteOutput
{
    public long? groupKey { get; set; }
    public string transOutput { get; set; }
    public long? transKey { get; set; }
    public string groupCode {get;set;}
    public string groupName {get;set;}
}

它有一个相应的值:

    groupKey:121
    transOutput: "Success"
    transKey:998546
    groupCode:"My Group Test"
    groupName: "My Created Group Test"

我想要的是......

我想阅读JSON文件,如果任何条目picklist_typ_key与传入对象groupKey匹配,我只想更新该对象picklist_typ_cd 1}} groupCodepicklist_typ_dscgroupName

我可以将JSON中的数据读作......

        if(gmwo.transOutput.ToUpper() == "SUCCESS")
        {
            string json = System.Configuration.ConfigurationManager.AppSettings["PicklistDataPath"];
            List<PicklistData> deserializedPicklistData = JsonConvert.DeserializeObject<List<PicklistData>>(System.IO.File.ReadAllText(json));

            //find the object that matches

            IEnumerable<PicklistData> results = deserializedPicklistData.Where(item => item.picklist_typ_key == gmwo.groupKey.ToString());

            if(results != null)
            {
                **//What is the logic to update only that entry in the json file** 
            }

请帮我做。

1 个答案:

答案 0 :(得分:0)

你能试试LINQ“All”链吗?像这样:

IEnumerable<PicklistData> results = deserializedPicklistData
  .Where(item => item.picklist_typ_key == gmwo.groupKey.ToString())
  .All(selectedItem => someFunction(selectedItem));

:
:

someFunction(PicklistData myPick) {
:
}