POJO with array of integers to deserialize - java

I am having some trouble deserializing the following JSON into a POJO. I have no control over the JSON structure, else I would've implemented it in some other way, but, that's life for you.
{
"1":{
"test":"1",
"other":"stuff"
},
"2":{
"test":"2",
"other":"stuff2"
}
}
Anyway, I am trying to deserialize by using a POJO with:
public Map<Integer, Payload> payload;
but although the Map does have a size of 2, when I try to get each of it, it's contents are null. Any idea on what I am doing wrong?
Thank you

I have no idea how the payload class looks like, but it should be something like this:
class Payload {
String test;
String other;
#Override
public String toString() {
return "Payload [test=" + test + ", other=" + other + "]";
}
}
If you assert this condition, then you can deserialize the json using a TypeToken> as token as danypata suggest... like:
public static void main(String args[]) throws InterruptedException {
String ff = "{\"1\":{" + "\"test\":\"1\"," + "\"other\":\"stuff\"" + "}," + "\"2\":{" + "\"test\":\"2\","
+ "\"other\":\"stuff2\"" + "}}";
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, Payload>>() {
}.getType();
Map<String, Payload> map = gson.fromJson(ff, mapType);
System.out.println(map);
for (Entry<String, Payload> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
giving as result:
{1=Payload [test=1, other=stuff], 2=Payload [test=2, other=stuff2]}
1
Payload [test=1, other=stuff]
2
Payload [test=2, other=stuff2]

Why don't you use the Android JSONObject class? Then you can parse with it your entire JSON string and then you can obtain the values easily. For example this is to get the values of your "1" JSON object:
final JSONObject jsonObject = new JSONObject(jsonString);
final String test = jsonObject.getJSONObject("1").getString("test");
final String other = jsonObject.getJSONObject("1").getString("other");

Related

Convert Json string into Hashmap of hashmap in java

I am new to json processing, below is the json string our clients send us, I want to
read this json string into a hashmap of hasmap so that even for the "Client"/"params" key below
I can access its key and value set and process them .
var incomingMessage =
"{
\"dev1\":\"NULL\",
\"devkp2\":\"val\",
\"compression\":\"NULL\",
\"subcode\":\"P_CODE\",
\"code\":\"PEB_USER\",
\"Client\":{
\"first_name\":\"Perf FN 422677\",
\"client_last_name\":\"DP_PSL\",
\"clientid\":\"780A832\",
\"email\":\"DP_PS#airb.com\"
},
\"clientsrc\":\"dev.client.notvalid\",
\"params\":{
\"Name\":\"ABC_PR\",
\"client_ID\":\"PSL\",
\"domain\":\"airb.com\"
}
}"
This is my current code which works fine for non-nested json strings (that is without the Client.params key in above json string):
public static void convertJsonStringToMap(String incomingMessage) {
HashMap<Object, Object> map = new HashMap<Object, Object>();
JSONObject jObject = new JSONObject(incomingMessage);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
for (Map.Entry<Object, Object> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
I want to be able to similarly read nested keys like Client and params. I am using jdk11. I am fine with using jackson or google gson, both approaches would work.
Please help me with processing these nested json string.
A valid JSON string can be easily converted to a Map using Jackson ObjectMapper.
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsedMap = mapper.readValue(incomingMessage, Map.class);
It works for nested elements as well -
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String someJsonString = "{" +
"\"A\":\"1\"," +
"\"B\":2," +
"\"C\":" +
"{" +
"\"D\":\"4\"" +
"}" +
"}";
Map<String, Object> outputMap = mapper.readValue(someJsonString, Map.class);
System.out.println(outputMap);
}
Output:
{A=1, B=2, C={D=4}}

Json map into java map

I have the following json file
[{
"en": {
"key1": "Ap",
"key2": "ap2"
}
},
{
"ar": {
"key1": "Ap",
"key2": "ap2"
}
}
]
I would like to create a Map in Java such as the key is the language (like en or ar) and the value is a object. Something like this.
public class Category {
private String key1;
private String key2;
}
Type type = new TypeToken<Map<String, Category>>() {}.getType();
Gson gson = new Gson();
InputStream in = MyClass.class.getResourceAsStream("/categories.json");
String text = IOUtils.toString(in, StandardCharsets.UTF_8);
Map<String, Category> map = gson.fromJson(text, type);
But when I run this code, I get errors:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $[0]
Is my Json structure wrong or is there an easier way to map this?
try to read this json file
{
"ar": {
"key1": "Ap",
"key2": "ap2"
},
"en": {
"key1": "Ap",
"key2": "ap2"
}
}
The above json is collection of JsonObject like list or array, so just parse it to List of Map objects
Type type = new TypeToken<List<Map<String, Category>>>() {}.getType();
Your json is a list of maps, not only maps. So you have to add it to the type declared.
Try this:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class Category {
private String key1;
private String key2;
#Override
public String toString() {
return "Category{" +
"key1='" + key1 + '\'' +
", key2='" + key2 + '\'' +
'}';
}
public static void main(String[] args) {
String json = "[{\n" +
" \"en\": {\n" +
" \"key1\": \"Ap\",\n" +
" \"key2\": \"ap2\"\n" +
" }\n" +
" },\n" +
"\n" +
" {\n" +
" \"ar\": {\n" +
" \"key1\": \"Ap\",\n" +
" \"key2\": \"ap2\"\n" +
" }\n" +
" }\n" +
"]";
Type type = new TypeToken<List<Map<String, Category>>>() {}.getType();
Gson gson = new Gson();
List<Map<String, Category>> maps = gson.fromJson(json, type);
System.out.println(maps);
}
}
Your input is an json array with two objects. However your target variable 'type' is a of type Object and not an 'Array of Objects'. In simpler terms, Map cannot store an
Array.
Lets take a simpler approach to this problem(not a recommended approach). If we convert the map manually to an array of maps, that would look like this:
yourJson -> [Map1(en,category1(Ap,ap2)),Map2(en,category2(Ap,ap2))]
i.e. An array of Maps
So in java equivalent this becomes:
Type typeOfT2 = new TypeToken<ArrayList<HashMap<String, Category>>>() {}.getType();
List<HashMap<String, Category>> list = gson.fromJson(text, typeOfT2);
We get to what we want, but there are better ways of doing this. We need Jackson instead of Gson for this.(Some one may add a Gson based solution, pretty sure a cleaner one than above exists). Here we will use ObjectMapper from com.fasterxml.jackson.databind.ObjectMapper
ObjectMapper om = new ObjectMapper();
List<Map.Entry<String, Category>> listx = om.readValue(text, ArrayList.class);
If you print listx. You can see this(overridden toString() of Category class):
[{en={key1=Ap, key2=ap2}}, {ar={key1=Ap, key2=ap2}}]
listx is the most accurate representation of your json and not a Map.
Now if you need a map, I will leave that as an exercise for you about how to convert your List of Map.Entry to a Map implementation.
PS.: First long answer here. Apologies for any mistakes.

How to parse JSON with JAVA when there are random key names

How do I convert some JSON to a POJO when I don't know the name of a key?
This is my POJO:
public class Summoner {
private Details summonerDetails;
public Details getSummonerDetails() {
return summonerDetails;
}
public void setSummonerDetails(Details summonerDetails) {
this.summonerDetails = summonerDetails;
}
}
The Details class have variables like id, name, etc. -> No issues here
This is the line in my Main class where I try to map the JSON to a POJO:
Summoner test = new ObjectMapper().readValue(json, Summoner.class);
this is a JSON response example I receive:
{
"randomName":{
"id":22600348,
"name":"Ateuzz",
"profileIconId":546,
"summonerLevel":30,
"revisionDate":1378316614000
}
}
if my POJO Details member variable name is "randomName", above code will work. but when I get a response with a different name than "randomName", it doesn't. How do I make my code work for random names?
I'm using Jackson
I'm sorry I can't make a little more clear my issue.
I have solution using not only jackson API but with the use of org.json API also.
String str = "{\"randomName\":{\"id\":22600348,\"name\":\"Ateuzz\",\"profileIconId\":546,\"summonerLevel\":30,\"revisionDate\":1378316614000}}";
JSONObject json = new JSONObject(str);
Iterator<?> keys = json.keys();
while(keys.hasNext())
{
String key = (String)keys.next();
Details test = new ObjectMapper().readValue(json.getJSONObject(key).toString(), Details.class);
}
Here i have use another JAVA Json API to convert your string into jsonObject and than iterate it to get your first key value and map that to your class Details.
I assume that your json format is same as you have mention in your question.
May this will help you.
Using Jackson:
String json = "{\"randomName\":{\"id\":22600348,\"name\":\"Ateuzz\",\"profileIconId\":546,\"summonerLevel\":30,\"revisionDate\":1378316614000}}";
try
{
#SuppressWarnings("unchecked")
Map<String, Map<String, Object>> map = (Map) new ObjectMapper().readValue(json, Map.class);
for(String key : map.keySet())
{
Map<String, Object> submap = map.get(key);
System.out.println(key + ":");
for(String k : submap.keySet())
{
System.out.println("\t" + k + ": " + submap.get(k));
}
}
}
catch(IOException e)
{
e.printStackTrace();
}

String value as Object key

Let's say I've got String A = "A"; and String B = "B"; and I want to use these values as keys in a json object.
{
"A":"string1",
"B":"string2"
}
Now in another time and space, I'd like to get these String values from the Json Object. I'd have to get the value for "A" and "B". We can just use A and B when making this json object and reuse them when getting the values.
However, I'm trying to make a Json Object from an actual Object. I'm using Gson to achieve this. How can I use A and B as keys when making the object?
Using Gson you can parse the JSON into a Map as
String json = "{\n" +
"\"A\":\"string1\",\n" +
"\"B\":\"string2\"\n" +
"}";
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(json, type);
System.out.println(map.get("A")); // string1
System.out.println(map.get("B")); // string2
Alternatively, if you want to wrap the keys in an already existing object
String json = "{ pairs : {\n" +
"\"A\":\"string1\",\n" +
"\"B\":\"string2\"\n" +
"} }";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
System.out.println(jsonObject.getPairs().get("A")); // string1
System.out.println(jsonObject.getPairs().get("B")); // string2
where the JsonObject could look like
class JsonObject {
private Map<String, String> pairs;
public Map<String, String> getPairs() {
return pairs;
}
}

Take Mustache Template, pass JSON and Convert to HTML

I am using this code below to merge JSON data into a template, to get HTML:
Template:
String schema = "<h1>{{header}}</h1>"
+ "{{#bug}}{{/bug}}"
+ "{{#items}}"
+ "{{#first}}"
+ "<li><strong>{{title}}</strong>
+ </li>"
+ "{{/first}}"
+ "{{#link}}"
+ "<li><a href=\"{{url}}\">{{name}}
+ </a></li>"
+ "{{/link}}"
+ "{{/items}}"
+ "{{#empty}}"
+ "<p>The list is empty.</p>"
+ "{{/empty}}";
JSON object:
try {
String template = "{\"header\": \"Colors\", "
+ "\"items\": [ "
+ "{\"name\": \"red\", \"first\": true, \"url\": \"#Red\"}, "
+ "{\"name\": \"green\", \"link\": true, \"url\": \"#Green\"}, "
+ "{\"name\": \"blue\", \"link\": true, \"url\": \"#Blue\"}"
+ " ], \"empty\": false }";
JSONObject jsonWithArrayInIt = new JSONObject(template);
JSONArray items = jsonWithArrayInIt.getJSONArray("items");
Map<String,String> ctx = new HashMap<String,String>();
ctx.put("foo.bar", "baz");
Mustache.compiler().standardsMode(true).compile("{{foo.bar}}").execute(ctx);
System.out.println("itemised: " + items.toString());
} catch(JSONException je) {
//Error while creating JSON.
}
I pass a map of data to get Mustache to work. The method looks like this:
public static Map<String, Object> toMap(JSONObject object)
throws JSONException {
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
I am following a Mustache Guide to get the Mustache autoformation. But I don't know how to get the result I am expecting. The output should be as follows:
<h1>Colors</h1>
<li><strong></strong></li>
<li>green</li>
<li>blue</li>
I think you need to rethink your Mustache template slightly. The jMustache library (which I assume you are using) seems to always treat {{# entities as lists and iterate their contents, regardless of the data type passed in.
Something like this should work:
<h1>{{header}}</h1>
{{#items}}
<li>
{{#url}}<a href="{{.}}">{{/url}}
{{^url}}<strong>{{/url}}
{{caption}}
{{#url}}</a>{{/url}}
{{^url}}</strong>{{/url}}
</li>
{{/items}}
{{^items}}
<p>The list is empty.</p>
{{/items}}
This will produce an HMTL anchor only if a "link" value is provided, thus avoiding the jMustache if condition issue. So the JSON model would look something like this:
{
"header": "Colors",
"items": [
{"caption": "title"},
{"caption": "red", "url": "#Red"},
{"caption": "green", "url": "#Green"},
{"caption": "blue", "url": "#Blue"}
]
}
Finally, you will need to convert your JSON to something jMustache understands. I've never seen or heard of the "HTTPFunctions" class in any library I've used, but I've done some similar mapping using Gson in the past. Note that this is a very simple implementation and you may need to extend it to fit your needs:
private Map<String, Object> getModelFromJson(JSONObject json) throws JSONException {
Map<String,Object> out = new HashMap<String,Object>();
Iterator it = json.keys();
while (it.hasNext()) {
String key = (String)it.next();
if (json.get(key) instanceof JSONArray) {
// Copy an array
JSONArray arrayIn = json.getJSONArray(key);
List<Object> arrayOut = new ArrayList<Object>();
for (int i = 0; i < arrayIn.length(); i++) {
JSONObject item = (JSONObject)arrayIn.get(i);
Map<String, Object> items = getModelFromJson(item);
arrayOut.add(items);
}
out.put(key, arrayOut);
}
else {
// Copy a primitive string
out.put(key, json.getString(key));
}
}
return out;
}
This basic JUnit test demonstrates the theory: http://www.pasteshare.co.uk/p/841/
Just use
Map<String, Object> s = HTTPFunctions.toMap(new JSONObject(template));

Categories