Use JPath but not recursively loop a JObject to modify the values.

I am dealing with a Json file, I parsed it into jObject, I have another list which flattened the properties of a jobject which share part of the property elements names. Now I want to modify values in the jobject according to values indicated in the list.
At first, I was recursively traversing and seeking tokes, and then edit the value, but it is very annoying and reads poorly, though it does achieve the same effect.
Then I realized there is jPath, which can find the dest token with expression. I then changed to using it. And finally there are not that many loops and recursions.
Some comparisons listed:

//the jobject
var a={a:{b:{c:3}}}
//the list
{"a:b:c" :3}

Using loop

                        //var newValObj = new JObject();
                        //var ret=new JObject();
                        //for (int i = 0; i < keyIndexerArray.Length; i++)
                        //{
                        //    var key = keyIndexerArray[i];
                        //    newVal[key] = new JObject();           
                        //    if(0==i)ret=newVal;
                        //    if (i == keyIndexerArray.Length - 1) newVal[key] = newSettingVal;
                       //    newVal = newVal[key] as JObject;
                        //}
                    }
                    //originalContent.Merge(newVal);

Using jpath

                     var newSettingVal = newItem.Value;
                        //JToken originalVal = originalContent;
                        var keyIndexerList = newItem.Key.Split(':').ToList();
                        var endingPath = keyIndexerList.Last();
                        keyIndexerList.RemoveAt(keyIndexerList.Count - 1);
                        var jPath = string.Join('.', keyIndexerList.ToArray());
                        var valueToken = originalContent.SelectToken(jPath);
                        valueToken[endingPath] = newSettingVal;

There is no merge, and every value is modified with this simple transformation. Loop the less the better, time complexity should have been reduced though I don't know how jPath is realized.
Some explanation and examples of using jPath by newtonsoft: Usage

And this short paragraph is not very expressive, but the key is to explain address changes in loops, note that, every reference is an address change, though it is not so evident in high level programming languages, but such code should always be explained in memory address maps.
And of course, it's to show off the English skill 😃 . Every commented Excellent by the native speakers is actually for this, not that much for the code, if only I am confusing.

posted @ 2019-03-08 09:30  calochCN  阅读(191)  评论(0编辑  收藏  举报