2017-11-13 8 views
1

에서 나는 다음과 같은 특성을했습니다이름 바꾸기 JProperty이 json.net

{ 
    "bad": 
    { 
    "Login": "someLogin", 
    "Street": "someStreet", 
    "House": "1", 
    "Flat": "0", 
    "LastIndication": 
    [ 
     "230", 
     "236" 
    ], 
    "CurrentIndication": 
    [ 
     "263", 
     "273" 
    ], 
    "Photo": 
    [ 
     null, 
     null 
    ] 
    } 
} 

내가 예를 들어 '좋은'로 '나쁜'에서이 이름을 변경하는 방법에 대해 설명합니다. 네, 아비 Bellamkonda

public static class NewtonsoftExtensions 
{ 
    public static void Rename(this JToken token, string newName) 
    { 
     var parent = token.Parent; 
     if (parent == null) 
      throw new InvalidOperationException("The parent is missing."); 
     var newToken = new JProperty(newName, token); 
     parent.Replace(newToken); 
    } 
} 

하여 확장 메서드를 보았다하지만 Newtonsoft.Json.Linq.JProperty 에 Newtonsoft.Json.Linq.JProperty를 추가 할 수 없습니다이 exeption에게

을 얻었다.

+0

가능한 중복 Json의 부동산 정보] (https://stackoverflow.com/questions/40002773/changing-key-of-an-property-in-json) –

+0

시원하게 보이지만 작동하지 않습니다. 이 예에서는, JObject의 루트 obj를 작성합니다. 하지만 제 경우에는 JProperty 배열을 가지고 있고 foreach에서 이것을 사용합니다. 'JArray curLog = JArray.Parse (currentJsonLog); curLog.Children () .ToList() .ForEach (O => o.Properties(). ToList() .ForEach (p => { 경우 (p.Name ==) "나쁜" {/ /p.ChangeKey("새 이름");}' – NisuSan

답변

1

는 다소 직관, 그 확장 방법은이 JProperty 아닌 JProperty 자체에 token이 통과한다고 가정합니다. 당신이 재산에 대한 참조가있는 경우이 건물의 Value 같은 그것을 호출하면

JObject jo = JObject.Parse(json); 
jo["bad"].Rename("good"); 

, 당신은 아직도 그 확장 방법을 사용할 수 있습니다 : 아마도이 쉽게 대괄호 구문을 사용할 수 있도록하는 것입니다 :

JObject jo = JObject.Parse(json); 
JProperty prop = jo.Property("bad"); 
prop.Value.Rename("good"); 

그러나 코드가 혼란 스러울 수 있습니다.

public static void Rename(this JToken token, string newName) 
{ 
    if (token == null) 
     throw new ArgumentNullException("token", "Cannot rename a null token"); 

    JProperty property; 

    if (token.Type == JTokenType.Property) 
    { 
     if (token.Parent == null) 
      throw new InvalidOperationException("Cannot rename a property with no parent"); 

     property = (JProperty)token; 
    } 
    else 
    { 
     if (token.Parent == null || token.Parent.Type != JTokenType.Property) 
      throw new InvalidOperationException("This token's parent is not a JProperty; cannot rename"); 

     property = (JProperty)token.Parent; 
    } 

    var newProperty = new JProperty(newName, property.Value); 
    property.Replace(newProperty); 
} 

은 그럼 당신은 할 수 있습니다 : 그것은 두 경우 모두에서 작동 할 수 있도록 확장 방법을 개선하기 위해 더 나은 것

JObject jo = JObject.Parse(json); 
jo.Property("bad").Rename("good"); // works with property reference 
jo["good"].Rename("better");  // also works with square bracket syntax 

바이올린 : [가 키 변경의 https://dotnetfiddle.net/RSIdfx