0

I'm using the Groovy JsonBuilder to generate JSON to send over HTTP. My problem is it's capitalising some of the keys in the map it's given.

I give it an object of this class:

public class TestSNP {
    private String snpID;

    TestSNP(String input) {
        snpID = input.split("\\s+")[1];
    }

    String getSNPID() {
        return snpID;
    }
}

This is the test that fails:

import groovy.json.*

class Test {
    @Test
        void jsonBuilderTest() {
            def testSNP = new TestSNP("1 rs444444 2 3")
            assert new groovy.json.JsonBuilder(testSNP).toString() == '{"snpID":"rs444444"}'
        }
}

I get

{"SNPID":"rs444444"}

instead of

{"snpID":"rs444444"}

(this is a simplified example demonstrating my problem)

kiml42
  • 638
  • 2
  • 11
  • 26
  • @tim_yates That would probably be useful, wouldn't it. I've added the line that's causing the trouble now. Thank you. – kiml42 Dec 09 '15 at 13:13
  • The answer is: It doesn't... Groovy is not capitalising the entries. They will keep whatever capitalisation they have in the maps... ie: `assert new groovy.json.JsonBuilder([[snps:[[snpID:'rs444444']]]]).toString() == '[{"snps":[{"snpID":"rs444444"}]}]'` will work fine in Groovy – tim_yates Dec 09 '15 at 13:19
  • Thanks, that does indeed work. Indicating the problem is with my class, as: assert new groovy.json.JsonBuilder([[snps:[new domain.SNP("1 rs444444 2 3")]]]).toString() == '[{"snps":[{"allele1":null,"position":2,"valid":true,"basePairCoordinate":3,"allele2":null,"snpID":"rs444444","chromasome":"1"}]}]' doesn't work. I'll see if I can work out a simplified example that has the same problem, to save putting my whole class in here. – kiml42 Dec 09 '15 at 13:27
  • Is the field (or getter) in your `SNP` class called `SNPID` or `getSNPID`? – tim_yates Dec 09 '15 at 13:31
  • Yes, that's exactly the problem. I worked it out while putting together the simplified example that's now in the question. I hadn't considered that it would have to use the getter, and therefore guess what conventions I was using for variable naming. – kiml42 Dec 09 '15 at 13:51

1 Answers1

2

Change:

String getSNPID() {
    return snpID;
}

to:

String getSnpID() {
    return snpID;
}

And it will work as you expect

tim_yates
  • 167,322
  • 27
  • 342
  • 338