0

I am trying to parse a Json file in Groovy which contains a List of Strings. Some of these Strings contain GString formatting, and so I hoped to parse these as GStrings instead of normal Strings.

For example, the member description in the following would contain 1 GString and 7 Strings:

{
  ... (other members)
  "description": [
    "This weapon features an alternate firing mode which shoots a tracker grenade.",
    "As a free action, you can switch to the alternate fire mode.",
    "Grenades can be fired up to 30 feet and detonate after 1 round.",
    "Creatures within 15 feet of the grenade must make a Dexterity saving throw.",
    "The save DC is equal to 8 + your Wisdom modifier + your proficiency bonus.",
    "On a failed save, a creature takes ${variables}.get('grenadeDamage').get(${level}) damage and is considered tagged for 2 rounds.",
    "On a success, a creature takes only half the damage and is not tagged.",
    "Attacks with this weapon against tagged creatures have advantage.",
    "However, if any creatures are tagged, this weapon can only attack those creatures."
  ],
  "grenadeDamage": [
    "1d4", "1d4", "1d4", "1d6", "1d6",
    "1d6", "1d8", "1d8", "1d8", "1d10",
    "1d10", "1d10", "2d6", "2d6", "2d6",
    "4d4", "4d4", "4d4", "5d4", "5d4"
  ]
}

(I am not used to formatting GStrings, so it may be incorrect, in which case I apologize)

A Map of the additional members (such as "grenadeDamage" in the Json file above) would contain mappings of their names to their respective Lists. These would then be passed into a class laid out as such:

class Gun
{
    private int level
    // ... (additional fields)
    private List<?> description
    private Map<String, List<String>> variables

    // ... (Constructors, methods, etc.)

    List<String> getDescription()
    {
        description
    }
}

The hope here is to convert any GStrings in the List to regular Strings when getDescription() is called at runtime.

In the given example, if the level field was 7, the 5th line of description would fill ${variables}.get('grenadeDamage').get(${level}) to the value 1d8, or the 7th item in grenadeDamage.

The issue with this is that when using a JsonSlurper to parse the Json file, description is created as a List<String> directly. Ideally, I would like to parse description without immediately enforcing the type as String.

Any comments, advice, and constructive criticism is welcome and appreciated!

Batte
  • 15
  • 4
  • You are aware, that this would replace to `[some:map].get('grenadeDamage').get(7)` (this exact text, **not** the dice)? I think you want `${variables.grenadeDamage[level]}` (which will explode once level grows to big). Anyway: have a look at: http://docs.groovy-lang.org/latest/html/documentation/template-engines.html – cfrick Jan 15 '20 at 22:38
  • transform strings to a templates http://docs.groovy-lang.org/latest/html/api/groovy/text/GStringTemplateEngine.html – daggett Jan 17 '20 at 10:13

0 Answers0