0

I have some json I have stored in a string array called jsonString. I want to pull items into unity game objects by searching by its meta key > value and returning the meta_value > value.

Here's a snippet from the json code to explain:

[
 {
    "meta_key": "contact-email",
    "meta_value": "info@test.com"
},
{
    "meta_key": "contact_web",
    "meta_value": "http:\/\/www.google.com"
},
{
    "meta_key": "Services_count",
    "meta_value": "1"
},
{
    "meta_key": "Services_rating",
    "meta_value": "4"
},
{
    "meta_key": "Price_count",
    "meta_value": "1"
   }
]

On the scene I have a gameobject with a text ui element.

In the C# script I have used a www request to load text I stored in a string called jsonString.

If I try debugging this works.

       (LitJSON DLL)
       private JsonData itemData;

        itemData = JsonMapper.ToObject(jsonString);
        Debug.Log(itemData[2]["meta_value"]);

so I can then assign it to the text element on the gameobject.

The problem is that this is very inefficient as the json file can change so I'll never know the right row to pull info from.

What I want to do :

  string email = returnValue("contact-email");

then

private string returnValue(string what){
    //Check the array by the meta keys and then give me the value of the meta value for that item.
 return foundItem;
}

Apologies if I'm not explaining it very clearly. Basically, how do I look up the correct value by using key as a search item?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Diego
  • 371
  • 1
  • 3
  • 13

3 Answers3

4

You can write

var meta_value = itemData
  .Where(x => x.meta_key == "WhatEverYouAreLookingFor")
  .Select(x => x.meta_value)
  .FirstOrDefault();

to look for a value based on a specific key in your structure.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Torben
  • 438
  • 1
  • 7
  • 22
2

If you are doing the operation over and over again, you could convert it to a dictionary:

var dict = itemData.ToDictionary(x => x.meta_key, x => x.meta_value);

And use it like this:

var meta_value = dict[what];

Where what is the key you are looking for.

vyrp
  • 890
  • 7
  • 15
0

Try deserializing JSON to object like:

class MetaObject
{
    string meta_key { get; set; }
    string meta_value { get; set; }
}
class Settings
{
    IEnumerable<MetaObject> MetaObjects { get; set; }
    string GetValueOfProp(string PropName){
        ...
    }
}

Here you can read more about it

Community
  • 1
  • 1
Geli Papon
  • 51
  • 6