1

I am writing an Android app that sends some data over JSON. I'm using GSON to Serialise/Deserialise my objects. I have this working with a few objects already, but one endpoint/object is giving me trouble.

The functionality of the app is basically multiple choice questions. The user can choose one of A, B, C or D for roughly 10 questions, and based on the selection, there's also a long value that is associated with this selection.

Here is an example of the JSON I am trying to POST:

{
    "user": "abcd1234",
    "pass": "abc123",
    "itemID": 1234,
    "listSelection": [
        ("A", 21),
        ("D", 18),
        ("B", 34),
        ...
    ]
}

So the trouble is with the listSelection object. I don't control the API. The owner sent me the above sample to use. I'd rather have it in the form of answer: A, value: 21 but the owner wants tuples.

I am trying to create the class in Java to make GSON create the above to send over POST to the API, but my understanding of this process is that GSON names the key based on the variable name. This is fine for the user, pass and itemID but for the items within the listSelection where the key is dynamic, this does not work. I'm not sure if I need to put it in a map, or if there's another way in GSON for dynamically setting the key.

I was thinking something like this:

public class AnswerSet {

    private String user;
    private String pass;
    private int itemID;
    private List<Answer> listSelection;
}

where the Answer class might be:

public class Answer {

    private String answer;
    private long answerValue;
}

But this will format the JSON incorrectly.

Can anyone help? Thanks.

5
  • Why the last thing you proposed would format incorrectly? Commented Jul 6, 2015 at 21:37
  • It will fomat in the form "answer": "A", "answerValue": 21 instead of "A" : 21 Commented Jul 6, 2015 at 21:40
  • I suppose you need implement custom serializer for Answer, take a look stackoverflow.com/questions/6856937/… Commented Jul 6, 2015 at 21:42
  • Those pairs must be referred to by same name. I think is not possible to have what you say. How could that be deserialized afterwards? Commented Jul 6, 2015 at 21:42
  • 1
    Are you sure that your answers are surrounded by ( ) and not { }? Commented Jul 6, 2015 at 21:48

1 Answer 1

1

That is not valid JSON (try running it through a validator), so I would not expect GSON to be able to parse it. You will have to implement your own parser or change the POST to valid JSON.

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

1 Comment

OK thanks, I managed to get the JSON changed to a valid format.

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.