Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

api - Update a value of a key value pair in a nested array in C#

I have the following json

  {"audit_entry": {
    "where_uri": "test.com/service/apps/171f0841-825b-4964-8f8c-0869650f14a6",
    "why_uri": "test.com/service/reference/reasons_for_change/43545kjhjhkj0869650f14a6",
    "who_uri": "test.com/service/users/4977dae1-a307-425f-980c-53413fef1b0f",
    "when_audited": "2018-11-13T20:20:39+00:00",
    "what_uri": "test.com/service/subjects/1bc67a71-8549-4ab8-9dd9-e44238198860",
    "what_changed": [
        {
            "attribute_name": "birth_year",
            "attribute_value": "1969",
            "attribute_change": null
        },
        {
            "attribute_name": "subject_reference",
            "attribute_value": "dsdsfg",
            "attribute_change": null
        }
        ]
    }

I want to be able to change the value of "attribute_value" in the second child of what_changed. i.e. index [1]. I have tried the following code:

        JObject jObj = JObject.Parse(jsonText);
        jObj["audit_entry"]["what_changed"]["attribute_name"[1]];

But I know I have an issue with syntax. Any ideas would be much appreciated. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the documentation on Getting values by Property Name or Collection Index using JObject.

You can see the usage of index in the code example :

string itemTitle = (string)rss["channel"]["item"][0]["title"];

In you code example it should be :

var toto = (string)jObj["audit_entry"]["what_changed"][1]["attribute_name"];

Live example

You can the use Modifying JSON as reference for the modification:

jObj["audit_entry"]["what_changed"][1]["attribute_name"] = "New Value";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...