The server I am working with returns an json object which contains a list of objects, not just one.
{
"1":{"id":"1","value":"something"},
"2":{"id":"2","value":"some other thing"}
}
I want to convert this json object into an object array.
I know I can use Gson, and create a class like this:
public class Data {
int id;
String value;
}
and then use
Data data = new Gson().fromJson(response, Data.class);
But it's only for the objects inside the json object. I don't know how to convert json object with number as keys.
Or alternatively I need to alter the server to response to something like this?:
{["id":"1","value":"something"],["id":"2","value":"some other thing"]}
But I don't want to change to server as I have to change all the client side codes.
Your JSON looks really weird. If you can't change it, you have to deserialize it to Map
. Example source code could looks like this:
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class GsonProgram {
public static void main(String... args) throws Exception {
Gson gson = new GsonBuilder().create();
String json = "{\"1\":{\"id\":\"1\",\"value\":\"something\"},\"2\":{\"id\":\"2\",\"value\":\"some other thing\"}}";
Type type = new TypeToken<HashMap<String, HashMap<String, String>>>() {}.getType();
Map<String, Map<String, String>> map = gson.fromJson(json, type);
for (Map<String, String> data : map.values()) {
System.out.println(Data.fromMap(data));
}
}
}
class Data {
private int id;
private String value;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "Data [id=" + id + ", value=" + value + "]";
}
public static Data fromMap(Map<String, String> properties) {
Data data = new Data();
data.setId(new Integer(properties.get("id")));
data.setValue(properties.get("value"));
return data;
}
}
Above program prints:
Data [id=2, value=some other thing]
Data [id=1, value=something]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With