JSON解析复杂对象

时间:2013-05-31 05:59:10

标签: c# .net json parsing

以下是JSON响应的类型,

{
  "?xml":{
    "@version":"1.0",
    "@encoding":"iso-8859-1"
  },
  "xmlreport":{
    "@title":"ABC: TEST Most Saved2",
    "@dates":"Week of May 19,2013",
    "columns":{
      "column":[
        {
          "@name":"Page",
          "@type":"dimension",
          "#text":"Page"
        },
        {
          "@name":"Events",
          "@type":"metric",
          "@hastotals":"true",
          "#text":"Events"
        }
      ]
    },
    "rows":{
      "row":[
        {
          "@rownum":"1",
          "cell":[
            {
              "@columnname":"page",
              "@csv":"\"http://www.ABC.com/profile/recipebox\"",
              "#text":"http://www.ABC.com/profile/recipebox"
            },
            {
              "@columnname":"events",
              "@percentage":"\"0.1%\"",
              "#text":"489"
            }
          ]
        },
        {
          "@rownum":"2",
          "cell":[
            {
              "@columnname":"page",
              "@csv":"\"http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c\"",
              "#text":"http://www.ABC.com/recip...c602e4-007b-43e0-aaab-2f9aed89524c"
            },
            {
              "@columnname":"events",
              "@percentage":"\"0.0%\"",
              "#text":"380"
            }
          ]
        }
      ]
    },
    "totals":{
      "pagetotals":{
        "total":{
          "@columnname":"events",
          "@value":"1820.000000",
          "#text":"1,820 (0.2%)"
        }
      },
      "reporttotals":{
        "total":{
          "@columnname":"events",
          "@value":"7838.000000",
          "#text":"7,838 (0.8%)"
        }
      },
      "timeperiodtotals":{
        "total":{
          "@columnname":"events",
          "@value":"955774.000000",
          "#text":"955,774 (100.0%)"
        }
      }
    }
  }
}

我无法解析该对象。请您帮我解析如何在解析后读取属性和元素。我正在使用C#

{ 
     XmlDocument doc = new XmlDocument();
     doc.LoadXml(XML);

     string jsonText = JsonConvert.SerializeXmlNode(doc);
     //var result = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(jsonText, "xmlreport");
     var results = JsonConvert.DeserializeObject<dynamic>(jsonText);

     JToken token = JObject.Parse(jsonText);
     var report = token["xmlreport"];
}

3 个答案:

答案 0 :(得分:1)

我对这个问题的理解是你有一些Xml,你需要发送json。在我们得到代码之前几点:

1)不要直接将xml转换为json,因为它会导致问题

2)将xml解析到最后的对象,然后计算出要返回的格式;将进出的内容分离将允许其中一个接口在将来发生变化而不会影响另一个接口,因为您可以调整映射

所以,代码......

基本上将xml解析为对象以允许进一步处理,然后以json的形式推出。

class Program
{
    private static string starting =
        "<xmlreport title=\"ABC: TEST Most Saved2\" dates=\"Week of May 19,2013\"><columns><column name=\"Page\" type=\"dimension\">Page</column><column name=\"Events\" type=\"metric\" hastotals=\"true\">Events</column></columns><rows><row rownum=\"1\"><cell columnname=\"page\" csv=\"http://www.ABC.com/profile/recipebox\">http://www.ABC.com/profile/recipebox</cell><cell columnname=\"events\" percentage=\"0.1%\">489</cell></row><row rownum=\"2\"><cell columnname=\"page\" csv=\"http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c\">http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c</cell><cell columnname=\"events\" percentage=\"0.0%\">380</cell></row></rows><totals><pagetotals><total columnname=\"events\" value=\"1820.00000\">1,820 (0.2%)</total></pagetotals><reporttotals><total columnname=\"events\" value=\"7838.000000\">7,838 (0.8%)</total></reporttotals><timeperiodtotals><total columnname=\"events\" value=\"955774.000000\">955,774 (100.0%)</total></timeperiodtotals></totals></xmlreport>";


    static void Main(string[] args)
    {
        // parse from xml to objects
        StringReader reader = new StringReader(starting);
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(XmlReport));
        var xmlreport = (XmlReport)xmlSerializer.Deserialize(reader);

        // todo: do some process mapping ...

        // parse out as json
        var json = JsonConvert.SerializeObject(xmlreport);

        Console.WriteLine(json);
        Console.ReadLine();
    }
}

[Serializable]
[XmlRoot(ElementName = "xmlreport")]
public class XmlReport
{
    [XmlAttribute(AttributeName = "title")]
    public string Title { get; set; }
    [XmlAttribute(AttributeName = "dates")]
    public string Dates { get; set; }

    [XmlArray(ElementName = "columns")]
    [XmlArrayItem(typeof(Column), ElementName = "column")]
    public Collection<Column> Columns { get; set; }
}

[Serializable]
public class Column
{
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "type")]
    public string Type { get; set; }
}

如果我没有正确解释它,我已经尝试将json解析为原始的xml以开始这样的appologies。我没有完成整个结构,但我希望上面的例子能让你了解如何完成其​​余的工作。

希望这有帮助。

答案 1 :(得分:0)

这样做的一种方法是获取您在那里的JSON对象的实际数据结构。

然后创建表示该数据结构的类(如果您可以获得完整的响应 - 拥有所有属性,您只需使用此site将其转换为类)。

之后,使用可用的不同库将该JSON对象反序列化到您的类中。样本可以是one

答案 2 :(得分:0)

使用此(JSon.NET),递归函数将所有键和值写入输出窗口。

        [TestMethod]
        public void ParseMePlease()
        {


            string s = @"{""?xml"":{""@version"":""1.0"",""@encoding"":""iso-8859-1""},
                            ""xmlreport"":{""@title"":""ABC: TEST Most Saved2"",""@dates"":""Week of May 19,2013"",
                            ""columns"":{""column"":[{""@name"":""Page"",""@type"":""dimension"",""#text"":""Page""},{""@name"":""Events"",""@type"":""metric"",""@hastotals"":""true"",""#text"":""Events""}]},
                            ""rows"":
                            {""row"":[{""@rownum"":""1"",""cell"":[{""@columnname"":""page"",""@csv"":""\""http://www.ABC.com/profile/recipebox\"""",""#text"":""http://www.ABC.com/profile/recipebox""},{""@columnname"":""events"",""@percentage"":""\""0.1%\"""",""#text"":""489""}]},
                            {""@rownum"":""2"",""cell"":[{""@columnname"":""page"",""@csv"":""\""http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c\"""",""#text"":""http://www.ABC.com/recip...c602e4-007b-43e0-aaab-2f9aed89524c""},{""@columnname"":""events"",""@percentage"":""\""0.0%\"""",""#text"":""380""}]}]},
                            ""totals"":{""pagetotals"":{""total"":{""@columnname"":""events"",""@value"":""1820.000000"",""#text"":""1,820 (0.2%)""}},
                            ""reporttotals"":{""total"":{""@columnname"":""events"",""@value"":""7838.000000"",""#text"":""7,838 (0.8%)""}},
                            ""timeperiodtotals"":{""total"":{""@columnname"":""events"",""@value"":""955774.000000"",""#text"":""955,774 (100.0%)""}}}}}";         
            var result=JsonConvert.DeserializeObject<object>(s);

            Debug.WriteLine("Right Click Result on quick watch for Result Views!(On Debug)"+result.ToString() );

            JObject jobject = ((Newtonsoft.Json.Linq.JObject)result);


            PrintDetail(jobject);

        }

        public void PrintDetail(JObject node)
        {
            foreach (var item in node)
            {                    
                Debug.WriteLine("Key:" + item.Key + " Value:" + item.Value);
                if (item.Value is JObject)
                {
                    PrintDetail((JObject)item.Value);
                }
            }
        }