需要帮助访问Json对象而不用它的名字C#

时间:2014-10-04 22:51:34

标签: c# json serialization

我正在使用json

{"bloxwich": { "id": 44068310, "name": "Bloxwich", "profileIconId": 663, "revisionDate": 1412456785000, "summonerLevel": 30 }}

但bloxwich将根据用户输入进行更改。

这是我可以用来为bloxwich

访问id的代码
        string result = getResponse("https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/" + summonerName + "?api_key=" + key);
        dynamic resultData = JsonConvert.DeserializeObject(result);
        Console.WriteLine(resultData.bloxwich.id);

但是我想知道我每次都能如何进入bloxwich部分,即使这个名字会有所不同。

我尝试使用像这样的for循环

   foreach (var item in resultData)
   {
            Console.WriteLine("Item: " + item[0].id);
   }

但是我收到以下错误:

System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=Cannot access child value on Newtonsoft.Json.Linq.JProperty.
  Source=Newtonsoft.Json
  StackTrace:
       at Newtonsoft.Json.Linq.JToken.get_Item(Object key)
       at CallSite.Target(Closure , CallSite , Object , Int32 )
       at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
       at ConsoleApplication1.Api.getSummonerID(String summonerName) in C:\Users\Admin\documents\visual studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Api.cs:line 147
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Admin\documents\visual studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 22
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

2 个答案:

答案 0 :(得分:0)

尝试类似

的内容
using System;
using Newtonsoft.Json.Linq;

JObject resultData = JObject.Parse(result);
foreach (var item in resultData)
{
    Console.WriteLine(item.Key); // this will print "bloxwich" for your example
    Console.WriteLine("Item: " + item.Value.SelectToken("id"));
}

答案 1 :(得分:0)

你尝试过这样的事吗?

Dictionary<string, dynamic> data = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(result);
var key = data.Keys.First();
var item = data[key];
Console.WriteLine("Id " + item.id); // here you have the id

我不知道在这种情况下使用字典是否完全正确,但也许它可以帮助你。