1

I have a JSON file containing Dialogue for an RPG I'm making, and I'd like to be able to place the players chosen name in it as it comes up. For example if the player's name was a

public string playerName = "Leon";

and in my JSON I had

"NPCIDxxGreeting":{
    "text": "Yo, _____, what's up?"
}

I'd like to be able to insert "Leon" wherever that blank space showed up in the dialogue JSON. Is there any way to do this?

1
  • 2
    Use tokens and string.Replace. For example var greeting = "hello $name" and greeting.Replace("$name", "Leon") Commented Jun 10, 2016 at 23:30

2 Answers 2

1

What you're trying to do is replace a token in your string with another string. If your JSON file looks like this:

{
    "NPCIDxxGreeting":{
        "text": "Yo, $name, what's up?"
    }
}

You can load this string and then replace $name with the playerName variable.

If you're using JSON.NET, you can parse the JSON file like this:

dynamic dialogue = JObject.Parse(json);

Then, pull the string out and replace the $name token:

var greeting = dialogue["NPCIDxxGreeting"].text.ToString();
var playerGreeting = greeting.Replace("$name", playerName);

Here's a fiddle that demonstrates it: Replace variable in JSON

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

Comments

0

.NET supports Json converting. So basically you read in the file contents and just parse the JSON information.

Example

public class Stats
{
    public int attack;
    public string playerName;
    public float speed;
    ......
}
public static List<string>GetJson()
{
    using (StreamReader r = new StreamReader("file.json"))
    {
        string json = r.ReadToEnd();
        List<Stats> stats = JsonConvert.DeserializeObject<List<Stats>>(json);
        return stats ; 
    }
}

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.