Home > OS >  How to refer to a value by key in unity Newtonsoftjson
How to refer to a value by key in unity Newtonsoftjson

Time:03-12

I am getting json string from database. It looks something like this:

{
  "0": "Test0",
  "1": "Testdwa",
  "2": "Testik",
  "3": "Tests"
}

The length can be indefinite (That is, there may not be 4, but more lines). But I can't figure out how to get values by key (That is, I want to get the string "Testik" by key "2"). I also use "Newtonsoft.Json" in my script.

But I am a beginner, so it is desirable that you explain something in simple terms.

CodePudding user response:

you have to parse a json at first

var jsonParsed=JObject.Parse(json);

after this you can use the object the same way as a dictionary

string testic = (string) jsonParsed["2"]; // "Testic"
//or
var testdwa = (string) jsonParsed["1"]; // "Testdwa"

another way is to deserialiaze json to c# object (Dictionary<string,string> in this case

Dictionary<string, string> dict= JsonConverter.ToObject<Dictionary<string,string>>(json);

you can get data the same way, only you don't need to cast them

string testic = dict["2"]; // "Testic"
  • Related