2016-06-27 2 views
0

JSON 표기법이 약간 복잡합니다. 특히 JSON과 처음 만났기 때문에 더욱 그렇습니다. 세 번째 파트 도구를 사용하여 JSON 내의 모든 관련 객체 및 배열에 대한 C# 클래스를 만들었지 만 일부 내부 객체는 건너 뜁니다. 그런 다음 누락 된 객체를 복사하고 그에 대한 클래스를 생성하여 적절하게 사용했습니다.JSON 구문 분석 문제 - C#

대부분의 데이터를 구문 분석하고 액세스 할 수 있지만 대부분의 내부 개체는 구문 분석되지 않습니다.

나를위한 장애물 중 하나는 JSON에 "value"라는 이름을 가진 이름/값 쌍이 둘 이상 포함되어 있다는 것입니다.

JSON 추출물 :

"controls": [ 
        { 
        "value": "<p>The Governments current tobacco control strategy Creating a Tobacco-Free Generation: A Tobacco Control Strategy for Scotland sets out the Governments vision for a tobacco-free Scotland by 2034. Our contribution to this strategy is through</p>\n<ul>\n<li>prevention</li>\n<li>protection</li>\n<li>smoking cessation services.</li>\n</ul>\n<p>Tobacco smoking is a major risk factor for</p>\n<ul>\n<li>coronary heart disease</li>\n<li>stroke</li>\n<li>peripheral vascular disease</li>\n<li>many respiratory conditions including COPD</li>\n<li>a range of cancers </li>\n</ul>\n<p>and many other diseases and conditions. It is a leading cause of preventable ill health, premature death and disability.</p>\n<p>The Governments strategy outlines the importance of reducing health inequalities and the role that reducing smoking rates in the most deprived communities can have on this.</p>", 
        "editor": { 
         "alias": "rte" 
        } 
        }, 
        { 
        "value": [ 
         { 
         "callToAction": { 
          "value": [ 
          { 
           "name": "Read Government’s tobacco control strategy (external website)", 
           "url": "http://www.gov.gov/Publications", 
           "target": "_blank", 
           "icon": "icon-link" 
          } 
          ], 
          "dataTypeGuid": "5befdwe546fb12-3bc2-4f39-bab3-7328dfg345382afe65", 
          "editorAlias": "callToAction", 
          "editorName": "URL" 
         } 
         } 
        ], 
        "editor": { 
         "alias": "callToAction" 
        }, 
        "guid": "e3as34dc2831-c4e8-8671-038c-15634see45de7b71a" 
        }, 
        { 
        "value": "<h2>Reducing tobacco-related inequalities </h2>\n<p>The European Regional Office of the World Health Organisation (WHO) has produced policy guidance focusing on reducing inequalities relating to tobacco smoking. The guidance looks at</p>\n<ul>\n<li>the widening socio-economic inequities in tobacco consumption</li>\n<li>how the use of tobacco contributes to health inequalities</li>\n<li>the complexity of smoking in terms of inequality</li>\n<li>how tobacco increases inequalities over the life course</li>\n<li>what tobacco policies need to consider to address inequalities.</li>\n</ul>\n<p>The guidance reports that</p>\n<ul>\n<li>A child born in a more socially deprived area of Scotland is more likely to be born into a family that smokes, is more likely to have a mother who smoked during her pregnancy and is more likely to be around smokers growing up. Children of smokers are more likely to start smoking themselves and continue to repeat the cycle of their own experience.</li>\n<li>People living in the most deprived areas are less likely to feel in control of their life, more likely to experience stress and mental health issues and be less aware of the harm of smoking and second hand smoke.</li>\n<li>When it comes to stopping smoking this group of smokers are more likely to smoke heavily and have a stronger nicotine dependence and therefore find it harder to stop. They are less likely to know where to get help, and have less encouragement and social support to quit.</li>\n<li>They are more likely to suffer financial hardship as a consequence of smoking related illness, more likely to live in poor housing and more likely to have other health problems made worse by smoking.</li>\n</ul>\n<p>You can read the full <a href=\"http://ec.europa.eu/health/social_determinants/key_documents/index_en.htm#anchor1\">‘Tobacco and inequities’ guidance</a> on the European Commission’s website (external website).</p>\n<p>Our tobacco control work is achieved by working in partnership with Government, local and national NHS Boards along with <a href=\"http://www.ashscotland.org.uk/\" target=\"_blank\">ASH Scotland</a> (external website) including the <a href=\"http://www.ashscotland.org.uk/alliances\" target=\"_blank\"> Tobacco-free Alliance</a> (external website).</p>\n<h2>Getting help with local tobacco planning</h2>\n<p>To help with local planning, Public Health Observatory() have created local tobacco control profiles which include indicators on </p>\n<ul>\n<li>adult smoking prevalence</li>\n<li>smoking during and post-pregnancy</li>\n<li>smoking cessation</li>\n<li>smoking related death and disease</li>\n<li>tobacco sales.</li>\n</ul>", 
        "editor": { 
         "alias": "rte" 
        } 
        }, 
        { 
        "value": [ 
         { 
         "callToAction": { 
          "value": [ 
          { 
           "name": "Visit the TEST online profiles tool (external website)", 
           "url": "http://www.TEST.org.uk/comparative-health/profiles/online-profiles-tool", 
           "target": "_blank", 
           "icon": "icon-link" 
          } 
          ], 
          "dataTypeGuid": "5bs3a232-3bc2-4f39-bab3-73283ewr82afe65", 
          "editorAlias": "callToAction", 
          "editorName": "URL" 
         } 
         } 
        ], 
        "editor": { 
         "alias": "callToAction" 
        }, 
        "guid": "25ese341-4c05-0c11-e643-3f3aderd84e8e3" 
        } 
       ] 

난 단지 첫 번째 개체 ({"value":"<p>The ....", "editor":{...}} 를 얻을 수 있지만 다음 두 번째 개체에 액세스 할 수없고 callToAction있다

어떤 도움이 크게 될 것입니다

필요한 경우 코드를 공유 할 수 있습니다. C# & Newtonsoft.Json.

클래스 : 여기

using Newtonsoft.Json; 

namespace CallToAction.Models 
{ 
    public class Control 
    { 

     [JsonProperty("value")] 
     public Value[] Value { get; set; } 

     [JsonProperty("editor")] 
     public Editor Editor { get; set; } 

    } 
} 

using Newtonsoft.Json; 

namespace CallToAction.Models 
{ 
    public class Value 
    { 

     [JsonProperty("callToAction")] 
     public CallToAction CallToAction { get; set; } 
    } 
} 

using Newtonsoft.Json; 

namespace CallToAction.Models 
{ 
    public class CallToAction 
    { 

     [JsonProperty("value")] 
     public Value2[] Value { get; set; } 

     [JsonProperty("dataTypeGuid")] 
     public string DataTypeGuid { get; set; } 

     [JsonProperty("editorAlias")] 
     public string EditorAlias { get; set; } 

     [JsonProperty("editorName")] 
     public string EditorName { get; set; } 
    } 
} 

그리고 내 로컬 컴퓨터에있는 파일에서 JSON을 구문 분석하는 코드 줄이 617,451,515,

@jeff의 메르 카도, 여기에 코드입니다.

Control values = JsonConvert.DeserializeObject<Control>(System.IO.File.ReadAllText(@"C:\\Folder\\CallToAction\\CallToAction\\Content\\Value.json")); 
+0

_ 항상 _ 코드를 공유하십시오. 우리는 코드 없이는 당신을 도울 수 없습니다. –

+0

이 사이트로 이동하면 액세스하는 방법을 알 수 있습니다. - http://www.jsoneditoronline.org/ –

+0

감사합니다. 그러나 사이트가 시간 초과되었습니다. – LiaqatG

답변

1

그것은 사용자 "controls": [{...}, {...}] 배열 다형성 표시 : 이것은 다양한 종류의 제어를 포함 할 수 있고,이 중첩 형 "editor.alias" 토큰에 의해 표시된다. 이것을 클래스 계층 구조로 모델링 한 다음 Deserializing polymorphic json classes without type information using json.net 행을 따라 역 직렬화 할 수 있습니다. 다음과 같이

귀하의 다형성 클래스 계층 구조를 모델링 할 수있다 : 사용

[JsonConverter(typeof(ControlBaseConverter))] 
public abstract class ControlBase 
{ 
    public Editor editor { get; set; } 
} 

public class Editor 
{ 
    public string alias { get; set; } 
} 

public class CallToActionValue 
{ 
    public string name { get; set; } 
    public string url { get; set; } 
    public string target { get; set; } 
    public string icon { get; set; } 
} 

public class CallToAction 
{ 
    public List<CallToActionValue> value { get; set; } 
    public string dataTypeGuid { get; set; } 
    public string editorAlias { get; set; } 
    public string editorName { get; set; } 
} 

public class CallToActionControlValue 
{ 
    public CallToAction callToAction { get; set; } 
} 

[JsonConverter(typeof(NoConverter))] 
public class CallToActionControl : ControlBase 
{ 
    public List<CallToActionControlValue> value { get; set; } 

    public string guid { get; set; } 
} 

[JsonConverter(typeof(NoConverter))] 
public class RteControl : ControlBase 
{ 
    public string value { get; set; } 
} 

public class RootObject 
{ 
    public List<ControlBase> controls { get; set; } 
} 

custom JSON converters 다음 다음

class ControlBaseConverter : JsonConverter 
{ 
    public override bool CanConvert(Type objectType) 
    { 
     return objectType == typeof(ControlBase); 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     if (reader.TokenType == JsonToken.Null) 
      return null; 
     var obj = JObject.Load(reader); 
     var editorValue = (string)obj.SelectToken("editor.alias"); 

     Type type; 
     if (string.Equals(editorValue, "rte", StringComparison.OrdinalIgnoreCase)) 
     { 
      type = typeof(RteControl); 
     } 
     else if (string.Equals(editorValue, "callToAction", StringComparison.OrdinalIgnoreCase)) 
     { 
      type = typeof(CallToActionControl); 
     } 
     else 
     { 
      throw new JsonSerializationException("Unknown type of Control: " + editorValue); 
     } 
     return obj.ToObject(type, serializer); 
    } 

    public override bool CanWrite { get { return false; } } 

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 
} 

public class NoConverter : JsonConverter 
{ 
    public override bool CanConvert(Type objectType) 
    { 
     return false; 
    } 

    public override bool CanRead { get { return false; } } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 

    public override bool CanWrite { get { return false; } } 

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 
} 

그리고 것은 수행

var root = JsonConvert.DeserializeObject<RootObject>(jsonString); 

는 파생 클래스에 [JsonConverter(typeof(NoConverter))] 추가 무한 재귀를 막을 때 기본 형식 변환기는 파생 형식을 deserialize하려고 시도합니다. 그렇지 않으면 [JsonConverter(typeof(ControlBaseConverter))] 특성이 상속됩니다.

샘플 fiddle.

+0

상세한 답변과 노력을 부탁드립니다. 이것은 실제 복잡한 작업으로 통합하는 데 다소 시간이 걸렸지 만, 대형 복합체에서 추출한 작은 (그러나 가장 안쪽의) 추출물이지만 잘 형성되지 않은 Json 객체는 아닙니다. – LiaqatG