C# - 如何在多维JSON中获取key的值

时间:2018-04-05 13:29:27

标签: c# json

我对C#很新,所以如果我问愚蠢的问题,请原谅。我正在使用Newtownsoft json。 (https://www.newtonsoft.com/json

这是我的代码:

public void SpawnPlayer(Dictionary<string, string> playerData, int cnnId)    
{

    string jsonData = JsonConvert.SerializeObject(playerData, Formatting.None);
    Console.WriteLine(jsonData);
}

以下是jsonData包含的内容:

  

{“1”:“{\ r \ n \”characterId \“:1,\ r \ n \”\ connectionId \“:1,\ r \ n   \“accountId \”:1,\ r \ n \“name \”:\“Riorage \”,\ r \ n \“level \”:2,\ r \ n   \“characterRace \”:1,\ r \ n \“\ characterClass \”:1,\ r \ n   \“characterPosition \”:{\ r \ n \“x \”:\“15.42661 \”,\ r \ n \“y \”:   \“7.477493 \”,\ r \ n \“z \”:\“ - 32.30045 \”,\ r \ n \“map \”:1 \ r \ n   },\ r \ n \“characterRotation \”:{\ r \ n \“x \”:\“1 \”,\ r \ n \“y \”:   \“203 \”,\ r \ n \“z \”:\“1 \”\ r \ n},\ r \ n \“charactrerInstance \”:   {\ r \ n \“instanceId \”:0,\ r \ n \“groupId \”:0 \ r \ n},\ r \ n   \“characterState \”:1,\ r \ n \“\”characterMovementState \“:0,\ r \ n   \“characterActionState \”:1,\ r \ n \“\ characterEmotionState \”:1,\ r \ n   \“lastOnline \”:\“5.4.2018г.14:59:16 \”,\ r \ n \“onlineTime \”:   \ “1 \” \ r \ N}“}

我想知道如何达到1CharacterPositionx的价值。

我想提供这些密钥并收到输出15.42661

是否有可能,如果是这样的话?

2 个答案:

答案 0 :(得分:0)

您可以尝试下面的一个:

string jsonData = JsonConvert.SerializeObject(playerData, Formatting.None);
var data = JsonConvert.DeserializeObject<dictionary<string,dictionary<string,object>>>(jsonData);
var x = data["1"]["CharacterPosition"].x;
Console.WriteLine(x);

答案 1 :(得分:0)

与@Aman建议的方式类似,但让dynamic在运行时处理类型:

dynamic d = JsonConvert.DeserializeObject("{'1':{'characterId':1,'connectionId':1,'accountId':1,'name':'Riorage','level':2,'characterRace':1,'characterClass':1,'characterPosition':{'x':'15.42661','y':'7.477493','z':'-32.30045','map':1},'characterRotation':{'x':'1','y':'203','z':'1'},'charactrerInstance':{'instanceId':0,'groupId':0},'characterState':1,'characterMovementState':0,'characterActionState':1,'characterEmotionState':1,'lastOnline':'5.4.2018г.14:59:16','onlineTime':'1'}}");

Console.Write(d["1"].characterPosition.x);

但是,您可以随时创建自己的课程并致电DeserializeObject<Class>

修改:查看此class generator