Reputation: 629
How can I parse this incorrect(I think) JSON using Gson library.
{
......
"phones":{
"155193":"5556739386",
"155194":"5555301828"
}
......
}
strings 155193
and 155194
are random values from server.
Need to use HashMap
or any ideas?
Upvotes: 1
Views: 115
Reputation: 6934
Your answer surely is right (don't forget to mark it as accepted!), but I have two notes that I put in form of answer.
First, if you can use also this way:
public class ServerResponse {
...
private Object phones;
...
}
you will receive anycase a Map, of course in this case you'll need a cast. So your solutions is better. But if the server sends you a list of phones, it will work however (of course you will have a class cast exception in your code instead of a JSONParsingException
Second, your JSON is not invalid, if you look at this, you'll see that is correctly parsed. What does not work here, is that you cannot follow the POJO approach to parse. One way is like you answered, another possibility is to write an adapter that returs you.. a Map. So it won't be a big deal, it's better to let Gson handle the situation as you did.
Upvotes: 1
Reputation: 629
For this situation it helped me:
public class ServerResponse {
...
private HashMap<String, String> phones;
...
}
Upvotes: 1