I have a JsonObject :
{"result":[{"active":"true"}]}
How can I get value of active?
You can use Jackson
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsedMap = mapper.readValue(jsonString, new TypeReference<HashMap<String, Object>>() {
});
We get a Map with key value pairs. With your input you will get a Map<List<Map<String,String>>>. So to get "active", you can use something like parsedMap.get("result").get(0).get("active") (Note: This is just a pseudo code)
Related
I am trying to understand/learn how to pull data from a weather API, i have successfully done that and i got a Json file filled with data. I managed with gson put the information into a Map.
But it also has nested json for key main were i'm pulling out value into what may by explicit typecasting.
The thing i would like to ask, is if there is a neater way of doing this and so that i don't need to do explicit type casting nested json into Map
Map<String, Object> resultMap = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, Object>>() {
}.getType());
for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
System.out.println(entry);
}
System.out.println(resultMap.get("temp"));
Map<String, Object> mainMap = (Map<String, Object>) resultMap.get("main");
System.out.println("Temp: " + mainMap.get("temp"));
This is my output in the console:
rain={}
visibility=10000.0
timezone=7200.0
main={temp=8.1, pressure=1007.0, humidity=93.0, temp_min=7.0, temp_max=10.0}
clouds={all=75.0}
sys={type=1.0, id=1788.0, country=SE, sunrise=1.571203601E9, sunset=1.571240388E9}
dt=1.571249075E9
coord={lon=18.06, lat=59.33}
weather=[{id=301.0, main=Drizzle, description=drizzle, icon=09n}]
name=Stockholm
cod=200.0
id=2673730.0
base=stations
wind={speed=3.6, deg=40.0}
null
Temp: 8.1
I would say you can convert the json string into Map<String, JsonElement> so that you have so methods to find nested object is JsonObject or JsonArray. So in the blow example main is key with JsonObject as value
main: {
temp:8.1,
pressure:1007.0,
humidity=93.0,
temp_min=7.0,
temp_max=10.0
}
You can parse the value into Map by using fromJson
Map<String, Object> resultMap = new Gson().fromJson(jsonString, new TypeToken<Map<String, Object>>() {
}.getType());
for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
System.out.println(entry);
}
System.out.println(resultMap.get("temp"));
Map<String, Object> mainMap = new Gson().fromJson(resultMap.get("main").toString(), new TypeToken<Map<String, Object>>() {
}.getType());
System.out.println("Temp: " + mainMap.get("temp"));
I'm trying to read data from this API https://coinmarketcap.com/api/
For this endpoint https://api.coinmarketcap.com/v2/ticker/.
I'm having issues mapping the data field to a POJO. The field really contains an array of objects but in terms of the json it's not really defined as an array.
i.e. instead of
data: [{"id":"1","name":"some object"},{"id":"5","name":"another object"},...]
the json has named fields like so
data: {"1":{"id":"1","name":"some object"},"5":{"id":"5","name":"another object"},...}
I can manually parse this using
objectMapper.readTree(new URL("https://api.coinmarketcap.com/v2/ticker/"));
but is there a way automatically map these to a List?
You can parse it into a map (as #teppic said) and then get the map values as a list.
To deserialize into a map, you can see the answer from this question: Deserializing into a HashMap of custom objects with jackson
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Theme.class);
HashMap<String, Theme> map = mapper.readValue(json, mapType);
Assuming you have a class called Item with the id and name fields, you can do this:
String json = "{\"1\":{\"id\":\"1\",\"name\":\"some object\"},\"5\":{\"id\":\"2\",\"name\":\"another object\"}}";
ObjectMapper mapper = new ObjectMapper();
// create your map type <String, Item>
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Item.class);
HashMap<String, Item> map = mapper.readValue(json, mapType);
// get the list
List<Item> list = new ArrayList<Item>(map.values());
System.out.println(list);
Output:
[Item [id=1, name=some object], Item [id=2, name=another object]]
Your other option would be a custom deserializer, or reading the tree as you mentioned.
try this
String json = "[{\"name\":\"Steve\",\"lastname\":\"Jobs\"}]";
JsonArray jArray = (JsonArray)new JsonParser().parse(json);
String sName = jArray.get(0).getAsJsonObject().get("name").getAsString());
String sLastName = jArray.get(0).getAsJsonObject().get("lastname").getAsString());
see you later.
I am trying to do HTTP PUT using org.apache.cxf.jaxrs.client.WebClient. Server expects the payload in format:
{"key":"mainkey","value":{\"intKey1\":\"value1\",\"intKey2":\"value2\"},"ttl":"100"}
however, I am ending up sending as below:
{"key":"mainkey","value":{"intKey1":"value1","intKey2":"value2"},"ttl":"100"}
(Note that internal key value needs an escape quotes)
Here is my code snippet:
private void callClient4(RestClient client) {
KeyValueMessage<String, Map<String, String>> kv = new KeyValueMessage<String, Map<String, String>>();
kv.setKey("mainkey");
kv.setTtl("100");
Map<String, String> map = new HashMap<>();
map.put("intKey1", "value1");
map.put("intKey2", "value2");
kv.setValue(map);
Response ret = client.getClient().accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).sync()
.put(Entity.json(kv));
}
What could be done to change the format as expected by server?
used com.fasterxml.jackson.databind.ObjectMapper to solve the problem
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValueAsString(map);
I am getting responses from server that are wrapped with some additional info. For example:
{
"response_a" : ...,
"some_metadata" : 1234,
"more_metadata" : abcd
}
or
{
"response_b" : [...],
"some_metadata" : 1234,
"more_metadata" : abcd
}
The "response_x" can be custom object, list or hashmap, it can have different name depending on request.
Is there a way deserialize just the response_x, or get it as string using jackson?
You can deserialize above JSON to Map and retrieve the property using get method:
ObjectMapper mapper = new ObjectMapper();
MapType mapType = mapper.getTypeFactory().constructMapType(HashMap.class, String.class, Object.class);
Map<String, Object> result = mapper.readValue(json, mapType);
Object responseX = result.get("response_x");
Is there a way to convert a String containing json to a HashMap, where every key is a json-key and the value is the value of the json-key? The json has no nested values. I am using the Gson lib.
For example, given JSON:
{
"id":3,
"location":"NewYork"
}
resulting HashMap:
<"id", "3">
<"location", "NewYork">
Thanks
Use TypeToken, as per the GSON FAQ:
Gson gson = new Gson();
Type stringStringMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(json, stringStringMap);
No casting. No unnecessary object creation.
If I use the TypeToken solution with a Map<Enum, Object> I get "duplicate key: null".
The best solution for me is:
String json = "{\"id\":3,\"location\":\"NewYork\"}";
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
map = (Map<String, Object>)gson.fromJson(json, map.getClass());
Result:
{id=3.0, location=NewYork}
I like:
private static class MyMap extends HashMap<String,String> {};
...
MyMap map = gson.fromJson(json, MyMap.class);