6

这是我拥有的 json 字符串。

{
    "?xml" : {
        "@version" : "1.0",
        "@encoding" : "UTF-8"
    },
    "DataFeed" : {
        "@FeedName" : "issuerDetails",
        "SecurityDetails" : {
            "Security" : {
                "SecurityID" : {
                    "@idValue" : "AAPL-NSDQ",
                    "@fiscalYearEnd" : "2016-12-31T00:00:00.00"
                },
                "FinancialModels" : {
                    "FinancialModel" : [{
                            "@id" : "780",
                            "@name" : "Estimates - Energy",
                            "@clientCode" : "A",
                            "Values" : [{
                                    "@name" : "EBITDA",
                                    "@clientCode" : "EBITDA",
                                    "@currency" : "C$",
                                    "Value" : [{
                                            "@year" : "2014",
                                            "#text" : "555.64"
                                        }, {
                                            "@year" : "2015",
                                            "#text" : "-538.986"
                                        }, {
                                            "@year" : "2016",
                                            "#text" : "554.447"
                                        }, {
                                            "@year" : "2017",
                                            "#text" : "551.091"
                                        }, {
                                            "@year" : "2018",
                                            "#text" : "0"
                                        }
                                    ]
                                }, {
                                    "@name" : "EPS",
                                    "@clientCode" : "EPS",
                                    "@currency" : "C$",
                                    "Value" : [{
                                            "@year" : "2014",
                                            "#text" : "0"
                                        }, {
                                            "@year" : "2015",
                                            "#text" : "-1.667"
                                        }, {
                                            "@year" : "2016",
                                            "#text" : "-1.212"
                                        }, {
                                            "@year" : "2017",
                                            "#text" : "0.202"
                                        }, {
                                            "@year" : "2018",
                                            "#text" : "0"
                                        }
                                    ]
                                }, {
                                    "@name" : "CFPS",
                                    "@clientCode" : "CFPS",
                                    "@currency" : "C$",
                                    "Value" : [{
                                            "@year" : "2014",
                                            "#text" : "3.196"
                                        }, {
                                            "@year" : "2015",
                                            "#text" : "-0.207"
                                        }, {
                                            "@year" : "2016",
                                            "#text" : "0.599"
                                        }, {
                                            "@year" : "2017",
                                            "#text" : "2.408"
                                        }, {
                                            "@year" : "2018",
                                            "#text" : "0"
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            }
        }
    }
}

如何选择#text2015、2016、2017 年的 EPS 数据?这是我到目前为止的查询:

JObject jsonFeed = JObject.Parse(jsonText);

var query = from security in jsonFeed.SelectTokens("DataFeed.SecurityDetails.Security")
        .SelectMany(i => i.ObjectsOrSelf())
    let finModels = security.SelectTokens("FinancialModels.FinancialModel")
        .SelectMany(s => s.ObjectsOrSelf()).FirstOrDefault()
    where finModels != null
    select new
    {
        FinModelClientCode = (string)finModels.SelectToken("Values[1].@clientCode"),
        FinModelYear2015 = (string)finModels.SelectToken("Values[1].Value[1].@year"),
        FinModelValue2015 = (string)finModels.SelectToken("Values[1].Value[1].#text"),
        FinModelYear2016 = (string)finModels.SelectToken("Values[1].Value[2].@year"),
        FinModelValue2016 = (string)finModels.SelectToken("Values[1].Value[2].#text"),
        FinModelYear2017 = (string)finModels.SelectToken("Values[1].Value[3].@year"),
        FinModelValue2017 = (string)finModels.SelectToken("Values[1].Value[3].#text"),
    };

这是我正在使用的 jsonExtensions:

public static class JsonExtensions
{
    public static IEnumerable<JToken> DescendantsAndSelf(this JToken node)
    {
        if (node == null)
            return Enumerable.Empty<JToken>();
        var container = node as JContainer;
        if (container != null)
            return container.DescendantsAndSelf();
        else
            return new[] { node };
    }

    public static IEnumerable<JObject> ObjectsOrSelf(this JToken root)
    {
        if (root is JObject)
            yield return (JObject)root;
        else if (root is JContainer)
            foreach (var item in ((JContainer)root).Children())
                foreach (var child in item.ObjectsOrSelf())
                    yield return child;
        else
            yield break;
    }

    public static IEnumerable<JToken> SingleOrMultiple(this JToken source)
    {
        IEnumerable<JToken> arr = source as JArray;
        return arr ?? new[] { source };
    }
}

问题是EPS不会总是在下一家公司处于同样的位置吗?因此,我希望查询搜索 EPS 客户端代码并返回上述年份的值,希望使用 DRY 方法。你能帮我完成我的查询吗?

注意: 我实际上是在下载一个 XML 字符串,将其转换为 JSON,然后对其进行解析。

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
jsonText = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);   

JObject jsonFeed = JObject.Parse(jsonText);
4

4 回答 4

5

我认为最简单的方法是将您的 json 反序列化为如下所示的具体对象

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

你的模型是

public class SecurityID
{
    [JsonProperty("@idValue")]
    public string IdValue { get; set; }
    [JsonProperty("@iscalYearEnd")]
    public string FiscalYearEnd { get; set; }
}

public class Time
{
    [JsonProperty("@year")]
    public string Year { get; set; }
    [JsonProperty("#text")]
    public string Text { get; set; }
}

public class FinancialModelItem
{
    [JsonProperty("@name")]
    public string Name { get; set; }
    [JsonProperty("@clientCode")]
    public string ClientCode { get; set; }
    [JsonProperty("@currency")]
    public string Currency { get; set; }
    public List<Time> Value { get; set; }
}

public class FinancialModel
{
    [JsonProperty("@id")]
    public string Id { get; set; }
    [JsonProperty("@name")]
    public string Name { get; set; }
    [JsonProperty("@clientCode")]
    public string ClientCode { get; set; }
    public List<FinancialModelItem> Values { get; set; }
}

public class FinancialModels
{
    public List<FinancialModel> FinancialModel { get; set; }
}

public class Security
{
    public SecurityID SecurityID { get; set; }
    public FinancialModels FinancialModels { get; set; }
}

public class SecurityDetails
{
    public Security Security { get; set; }
}

public class DataFeed
{
    [JsonProperty("@FeedName")]
    public string FeedName { get; set; }
    public SecurityDetails SecurityDetails { get; set; }
}

public class Xml
{
    [JsonProperty("@version")]
    public string Version { get; set; }
    [JsonProperty("@encoding")]
    public string Encoding { get; set; }
}

public class RootObject
{
    [JsonProperty("?xml")]
    public Xml Xml { get; set; }
    public DataFeed DataFeed { get; set; }
}

你的查询现在是

    var result = root.DataFeed.SecurityDetails.Security.FinancialModels.FinancialModel
                .FirstOrDefault()?.Values
                .FirstOrDefault(x => x.Name == "EPS")
                .Value
                .Where(x => new[] { "2015", "2016", "2017" }.Contains(x.Year))
                .Select(x => x.Text)
                .ToList();
于 2016-09-20T20:11:06.163 回答
2

关于什么:

var jsonFeed = JObject.Parse(jsonText);
var epsToken = jsonFeed.SelectToken("$..Values[?(@.@name=='EPS')]");            
var year2014 = epsToken.SelectToken("Value[?(@.@year=='2014')].#text").ToString();
var year2015 = epsToken.SelectToken("Value[?(@.@year=='2015')].#text").ToString();
var year2016 = epsToken.SelectToken("Value[?(@.@year=='2016')].#text").ToString();
var year2017 = epsToken.SelectToken("Value[?(@.@year=='2017')].#text").ToString();

更通用的方法,它将选择所有年份和值:

var jsonFeed = JObject.Parse(jsonText);
var epsToken = jsonFeed.SelectToken("$..Values[?(@.@name=='EPS')]");            
var years = epsToken.SelectToken("Value")
                    .Select(i => new
                    {
                        Year = i.Value<string>("@year"),
                        Value = i.Value<decimal>("#text")
                    });

$..意味着我们将从文档的开头开始搜索,遍历所有节点并搜索Values等于@name. EPS基本上,介于?(和之间,)您正在输入令牌必须满足才能被选中的条件。@表示当前节点,因此@.@name转换为current node which has child node with name '@name'(我们EPS在示例中进行了比较)。

您将在此处找到更多信息:http JPath: //goessner.net/articles/JsonPath


注意到您更新了您正在处理 XML 的答案,因此基础知识保持不变:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
var epsNode = doc.SelectSingleNode("//Values[@name='EPS']");
var years = epsNode.SelectNodes("Value")
                   .Cast<XmlNode>()
                   .Select(i => new
                   {
                       Year = i.Attributes["year"].Value,
                       Value = decimal.Parse(i.InnerText)
                   });

尚未在您的 XML 上对其进行测试。另外,请注意i.Attributes["year"]可能是null,因此也要对其进行测试。

于 2016-09-19T20:36:01.890 回答
2

您从 XML 数据开始……为什么不将其作为 XML 数据进行处理。

var name = "EPS";
var years = new[] { "2015", "2016", "2017" };
var xpath = $"//Values[@name='{name}']/Value[{String.Join(" or ", years.Select(y => $"@year='{y}'"))}]";
var values = doc.XPathSelectElements(xpath).Select(e => (decimal)e);

否则,如果您必须坚持将其作为 json 使用,那么您可以这样做:

var name = "EPS";
var years = new[] { "2015", "2016", "2017" };
var jpath = $"$..Values[?(@.@name=='{name}')].Value[?({String.Join(" || ", years.Select(y => $"@.@year=='{y}'"))})].#text";
var values = jsonFeed.SelectTokens(jpath).Select(v => (decimal)v);
于 2016-09-19T21:14:15.180 回答
1

如果您确定这将是 json 格式,您可以创建一个代表 json 对象的类并让一些库(如 JconConvert)进行解析。从那里应该很容易。

于 2016-09-16T18:47:33.563 回答