1

I have a simple json string that my php file return to unity {"1":10,"2":25,"3":1,"4":124,"7":567} first number is the item id and 2nd is the amount.

I see in unity and c# unlike php that arrays are a fixed length so it seems that the best way is to parse into either a dictionary or list.

Anyone know the best way to parse this in 2020, not sure wether unity has its own json parser now or if you should use simpleJson and what would be the best way to store it.

I have a dictionary for the gameitems but not sure how to get the json string into it

Dictionary<int, int> Gameitems = new Dictionary<int, int>();

Adam
  • 87
  • 6
  • 2
    have you done any research at all? this is just one google answer away...\ – sommmen Apr 13 '20 at 15:50
  • 1
    Yes i have done a ton of research on the fact but all the answers are from 2,3 or 4 years ago and use Outside JSON API's...I read a few saying in 2019 unity would have it's own json parser hence why i am asking the question here before i go and import an entire api to do something so simple. I have got the Dictionary Gameitems = new Dictionary(); to store all the game items but not sure how to parse the json into it in 2020. – Adam Apr 13 '20 at 16:07
  • if i type in 'Unity json' in google the first hit is https://docs.unity3d.com/Manual/JSONSerialization.html which is your answer. – sommmen Apr 13 '20 at 16:08
  • 1
    yes i saw that but that is taking a json object and turning it into a string. I looking in that page for how to take a json string and put it into a dictionary but i could not find anthing...Is there a simple command to do this or will i manually have to put the data into the dictionary? – Adam Apr 13 '20 at 16:12
  • good to hear - you could post it as an answer yourself and accept it – sommmen Apr 14 '20 at 07:29

1 Answers1

2

You can use NuGet package Newtonsoft and use this simple function:

    JsonConvert.DeserializeObject<Dictionary<int, int>>( yourJsonString );

But unfortunately, unity doesn't support NuGet package manager so you'll have to import it to Unity manually. Here is the link on NuGet package Newtonsoft. It may be useful. More info about similar solution here

Or write your own parser : /


Update

As of February 2022 Newtonsoft may now be obtained directly from Unity here: Newtonsoft Json Unity Package. Just add com.unity.nuget.newtonsoft-json via the package manager. For details see Install official via UPM by kalle (jag).

dbc
  • 104,963
  • 20
  • 228
  • 340