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": "[email protected]"
},
{
    "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?

2
  • Can't you store the data in a dictionary? Commented Apr 27, 2017 at 13:48
  • Or in this specific case, a StringDictionary may be an even more appropriate type to use for storage. Commented Apr 27, 2017 at 13:56

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.