访问JSON C#动态变量中的数据

时间:2018-03-14 02:13:13

标签: c# json parsing

我正在处理/消费来自https://ashesescalation-api-tachyon.stardock.net/v1/products/2641/leaderboards/ladder/de5bfc9a-9092-4014-b52e-89151de42646?offset=0&count=2的一些数据(可以在Firefox中轻松打开以查看。)

我可以通过这样做来访问C#中的数据: 数据是json数据......

dynamic players = JArray.Parse(data);
var p = players[0];
Console.Write(p.personaName);

但是我无法访问JSON数据中的部分:“dataInteger”,例如“totalUnitsKilled”。

p.dataInteger[0].totalUnitsKilled

“p.dataInteger [0] .totalUnitsKilled”不起作用。

如何在C#中访问该数据?

非常感谢你的帮助。

沃伦

See image in visual studio 1

See image in visual studio 2

3 个答案:

答案 0 :(得分:0)

Kinldy在您的问题中查看我的评论,根据您需要使用JsonProperty映射具有特殊字符的密钥并根据您的需要手动命名的链接。

无论如何,您可以执行以下操作以达到您的需要。

  1. 将您的链接复制到http://json2csharp.com/
  2. 复制生成的快速类型并将其粘贴到您的代码中。
  3. 使用JsonProperty在您的媒体资源上显示名称的属性,手动重命名属性包含 invalid_name
  4. DeserializeObject对象。
  5. 以下是代码:

    从生成的快速类型中声明类。

    public class DataInteger
    {
        [JsonProperty(PropertyName = "totalUnitsKilled ")]
        public int totalUnitsKilled { get; set; }
        public int totalTitansKilled { get; set; }
        public int totalTimePlayed { get; set; }
        [JsonProperty(PropertyName = "substrate-TotalGamesPlayed")]
        public int SubstrateTotalGamesPlayed { get; set; }
        [JsonProperty(PropertyName = "phC-TotalGamesPlayed")]
        public int PHCTotalGamesPlayed { get; set; }
        public int lastReplayVersion { get; set; }
        public int replayUploadedCount { get; set; }
    }
    
    public class RootObject
    {
        public string personaLadderId { get; set; }
        public int rank { get; set; }
        public string personaId { get; set; }
        public string personaName { get; set; }
        public string avatarUrl { get; set; }
        public string avatarUrlSmall { get; set; }
        public string avatarUrlMedium { get; set; }
        public string avatarUrlLarge { get; set; }
        public string ladderType { get; set; }
        public string ladderId { get; set; }
        public string seasonId { get; set; }
        public int bracketId { get; set; }
        public string bracketName { get; set; }
        public int rankingScore { get; set; }
        public int secondaryScore { get; set; }
        public int ruleTypeId { get; set; }
        public int wins { get; set; }
        public int losses { get; set; }
        public int ties { get; set; }
        public int tieStreak { get; set; }
        public int winStreak { get; set; }
        public int lossStreak { get; set; }
        public int longestTieStreak { get; set; }
        public int longestWinStreak { get; set; }
        public int longestLossStreak { get; set; }
        public int bracketMaxScore { get; set; }
        public int bracketScore { get; set; }
        public DateTime updateDate { get; set; }
        public int totalMatchesPlayed { get; set; }
        public DataInteger dataInteger { get; set; }
    }
    

    调用API( Magic从这里开始

    var httpClient = new HttpClient();
    
    var link = $@"https://ashesescalation-api-tachyon.stardock.net/v1/products/2641/leaderboards/ladder/de5bfc9a-9092-4014-b52e-89151de42646?offset=0&count=2";
    
    var response = await httpClient.GetAsync(link);
    var contents = await response.Content.ReadAsStringAsync();
    
    //deserialized json result object...
    dynamic json = JsonConvert.DeserializeObject(contents);
    foreach (var item in json)
    {
        //deserialized again the item
        var data = JsonConvert.DeserializeObject<RootObject>(Convert.ToString(item));
        //you can now access all the properties including dataInteger.
        Console.WriteLine(Convert.ToString(data.dataInteger.totalUnitsKilled));
        Console.WriteLine(Convert.ToString(data.dataInteger.totalTitansKilled));
    }
    

    enter image description here

    <强>更新

    如果您不想使用强类型类,可以使用JArray

    进行解析
    JArray jsonVal = JArray.Parse(contents) as JArray;
    dynamic items = jsonVal;
    foreach (dynamic item in items)
    {
        var x = item.dataInteger;
        //you can access the fields inside dataInteger.
        Console.WriteLine(x["totalUnitsKilled "]);
        Console.WriteLine(x["phC-TotalGamesPlayed"]);
        Console.WriteLine(x["substrate-TotalGamesPlayed"]);
    }
    

    希望这会对你有所帮助。

答案 1 :(得分:0)

根据其他用户的建议,如果将其更改为“totalUnitsKilled”,则属性名称“totalUnitsKilled”中会有一个空格。下面的代码可以正常工作: -

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.nic.edudel.doe.firebaseauthentication.MainActivity">


    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="64dp"
        android:layout_marginStart="64dp"
        android:layout_marginTop="35dp"
        android:ems="10"
        android:hint="Email"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_alignStart="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="52dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="32dp"
        android:layout_marginStart="32dp"
        android:text="Register" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button2"
        android:layout_alignBottom="@+id/button2"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginEnd="28dp"
        android:layout_marginRight="28dp"
        android:text="Reset Password" />

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button3"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="76dp" />


</RelativeLayout>

答案 2 :(得分:-1)

您的JSON字符串错误。

[{"personaLadderId":"371eaf1c-4cfe-4873-af41-56e0cb9fcf91","rank":1,"personaId":"55834d01-13f3-445e-861f-0bc4769d87cc","personaName":"Amelie","avatarUrl":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg","avatarUrlSmall":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg","avatarUrlMedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_medium.jpg","avatarUrlLarge":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_full.jpg","ladderType":"Ranked","ladderId":"de5bfc9a-9092-4014-b52e-89151de42646","seasonId":"fd7dd807-4ac2-40ec-8476-a4b2937f70af","bracketId":0,"bracketName":"Legendary","rankingScore":38,"secondaryScore":2054,"ruleTypeId":1,"wins":374,"losses":32,"ties":0,"tieStreak":0,"winStreak":8,"lossStreak":0,"longestTieStreak":0,"longestWinStreak":61,"longestLossStreak":3,"bracketMaxScore":0,"bracketScore":0,"updateDate":"2018-03-03T14:13:09.647Z","totalMatchesPlayed":406,"dataInteger":{"totalUnitsKilled ":92615,"totalTitansKilled":14,"totalTimePlayed":294676,"substrate-TotalGamesPlayed":127,"phC-TotalGamesPlayed":6,"lastReplayVersion":265301040,"replayUploadedCount":160}},{"personaLadderId":"f0dd3482-f057-44d6-a626-9c9389ad2583","rank":2,"personaId":"b53815ab-d753-4415-9ea6-03a4519c3222","personaName":"Rebellions","avatarUrl":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b.jpg","avatarUrlSmall":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b.jpg","avatarUrlMedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b_medium.jpg","avatarUrlLarge":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b_full.jpg","ladderType":"Ranked","ladderId":"de5bfc9a-9092-4014-b52e-89151de42646","seasonId":"fd7dd807-4ac2-40ec-8476-a4b2937f70af","bracketId":0,"bracketName":"Legendary","rankingScore":38,"secondaryScore":2049,"ruleTypeId":1,"wins":767,"losses":188,"ties":0,"tieStreak":0,"winStreak":3,"lossStreak":0,"longestTieStreak":0,"longestWinStreak":52,"longestLossStreak":6,"bracketMaxScore":0,"bracketScore":0,"updateDate":"2017-10-29T18:03:33.92Z","totalMatchesPlayed":955,"dataInteger":{"totalUnitsKilled ":293274,"totalTitansKilled":88,"totalTimePlayed":924881,"phC-TotalGamesPlayed":4,"substrate-TotalGamesPlayed":350,"lastReplayVersion":250285270,"replayUploadedCount":703}}]

您的json密钥名称中有一个空格(&#34; totalUnitsKilled&#34;),它最终会转换为变量名称。

更正您的JSON密钥名称将解决此问题。还有其他键也有错误。

您可以在http://json2csharp.com/查看。无论它在哪里&#34; invalid_name &#34;,密钥名称都是错误的。

public class DataInteger
{
    public int __invalid_name__totalUnitsKilled  { get; set; }
    public int totalTitansKilled { get; set; }
    public int totalTimePlayed { get; set; }
    public int __invalid_name__substrate-TotalGamesPlayed { get; set; }
    public int __invalid_name__phC-TotalGamesPlayed { get; set; }
    public int lastReplayVersion { get; set; }
    public int replayUploadedCount { get; set; }
}

public class RootObject
{
    public string personaLadderId { get; set; }
    public int rank { get; set; }
    public string personaId { get; set; }
    public string personaName { get; set; }
    public string avatarUrl { get; set; }
    public string avatarUrlSmall { get; set; }
    public string avatarUrlMedium { get; set; }
    public string avatarUrlLarge { get; set; }
    public string ladderType { get; set; }
    public string ladderId { get; set; }
    public string seasonId { get; set; }
    public int bracketId { get; set; }
    public string bracketName { get; set; }
    public int rankingScore { get; set; }
    public int secondaryScore { get; set; }
    public int ruleTypeId { get; set; }
    public int wins { get; set; }
    public int losses { get; set; }
    public int ties { get; set; }
    public int tieStreak { get; set; }
    public int winStreak { get; set; }
    public int lossStreak { get; set; }
    public int longestTieStreak { get; set; }
    public int longestWinStreak { get; set; }
    public int longestLossStreak { get; set; }
    public int bracketMaxScore { get; set; }
    public int bracketScore { get; set; }
    public DateTime updateDate { get; set; }
    public int totalMatchesPlayed { get; set; }
    public DataInteger dataInteger { get; set; }
}

您可以使用JSON.Net属性来定义与JSON密钥名称相关的C#变量。查看this了解详情。

您的新课程应如下所示:

public class DataInteger
{
    [JsonProperty(PropertyName = "totalUnitsKilled ")]
    public int totalUnitsKilled { get; set; }
    public int totalTitansKilled { get; set; }
    public int totalTimePlayed { get; set; }
    [JsonProperty(PropertyName = "substrate-TotalGamesPlayed")]
    public int substrateTotalGamesPlayed { get; set; }
    [JsonProperty(PropertyName = "phC-TotalGamesPlayed")]
    public int phCTotalGamesPlayed { get; set; }
    public int lastReplayVersion { get; set; }
    public int replayUploadedCount { get; set; }
}