Convert JSONArrays into Map using Java - java

Trying to write a java class which convert JSON into Map by giving key. Sample method format and steps are below:
public Map<String, Map<String, String> convert(String jsonBody, String key){
Map<String, Map<String, String>> dataMap = new HashMap<String, Map<String, String>>();
Map<String, String> singleEntry = new HashMap<String, String>();
//Iterator<String> --get key from jsonBody
while(itr.hasNext()){
for(upto arary count){
singleEntry.put(jsonBody.getKey(i), jsonBody.getValue(i));
}
dataMap.put(itr.next(), singleEntry);
}
System.out.println(dataMap);
return data;
}
Sample JSON
[
{
"id": 146,
"Name": "John",
"LastName": "Mack",
},
{
"id": 148,
"Name": "Sam",
"LastName": "Rick",
}
]
Expected Output:
id -146, {id=146, Name = John, LastName =Mack}
id -148, {id=148, Name = Sam, LastName =Rick}
Please suggest best API and correct approach. Thanks in Advance.

See here for how to convert a json node to a Map.
See here about how to convert the json array to a map.

Related

Using HashMap to create complex JSON

I have spent a few days googling this various ways and don't see any that give examples of using HashMap - instead they all refer to Jackson or GSON. I am not able to use these as they cause an issue in Jenkins that will not be addressed (basically everything is super locked down and the work place will not "open" up alternatives)
I have a JSON body that I am attempting to send to a create record API.
For simple JSON body the process is pretty straightforward:
Desired JSON:
{
"owner": {
"firstName": "Steve",
"lastName": "Guy",
"Hair": "brown",
"Eyes": "yes"
"etc": "etc"
},
"somethingElse": "sure"
}
would look like
Map<String,Object> jsonRequest = new HashMap<>();
Map<String,String> ownerMap = new HashMap<>();
HashMap<Object, String> OwnerMap = new HashMap<Object, String>;
OwnerMap.put("firstName","Steve");
OwnerMap.put("lastName","Guy");
OwnerMap.put("Hair","brown");
OwnerMap.put("Eyes","yes");
OwnerMap.put("etc","etc");
jsonRequest.put("owner", OwnerMap);
jsonRequest.put("somethingElse", "sure");
Easy enough
If the JSON gets slightly more complex, I can't seem to figure it out.. and again I cannot use any other dependency for this.
so if I have a JSON Body that I need to send :
{
"customer": {
"address": [
{
"address": "Blah"
}
]
},
"anotherThing": "thing"
}
the same pattern does not work.
Map<String,Object> jsonRequest = new HashMap<>();
Map<String,String> ownerMap = new HashMap<>();
HashMap<Object, String> addressMap = new HashMap<Object, String>;
addressmap.put("address","Blah");
jsonRequest.put("address", addressMap);
jsonRequest.put("owner", OwnerMap);
jsonRequest.put("anotherThing", "thing");
returns as:
{
"owner": {
},
"anotherThing": "thing",
"address": {
"address": "Blah"
}
}
You seem to assume that the inner (for want of a better word) Maps need to be Map<*, String>, and that Map and String are the only things which extend Object.
Something like the following should work fine:
Map<String, Object> json = new HashMap<>();
Map<String, Object> customer = new HashMap<>();
// Could make this a Map<String, Object>[] (array) depending
// on json library used... You don't specify.
List<Map<String, Object>> address = new ArrayList<>();
Map<String, Object> innerAddress = new HashMap<>();
innerAddress.put("address", "Blah");
address.add(innerAddress);
customer.put("address", address);
json.put("customer", customer);
json.put("anotherThing", "thing");

Itterate through List of objects recieved in JSON

I have the following JSON data:
[
{
"id": 4,
"siteName": "site1",
"addressLine1": "address1",
"addressLine2": "address2",
"town": "town1",
"postcode": "postcode1",
"contactName": "name1",
"contactNumber": "number1",
"contactEmail": "email1"
},
{
"id": 5,
"siteName": "site2",
"addressLine1": "address1",
"addressLine2": "address2",
"town": "town1",
"postcode": "postcode1",
"contactName": "name1",
"contactNumber": "number1",
"contactEmail": "email1"
},
]
I'm parsing the data but it simply outputs one long string. I'd like to access each element within each object.
UPDATE: I'm outputting the individual elements, but for some reason the 'id' property is considered a double?
Map<String,Object> jsonArr = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
java.util.List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)jsonArr.get("root");
for(Map<String, Object> obj : content) {
Log.p((int)obj.get("id"));
Log.p((String)obj.get("siteName"));
Log.p((String)obj.get("addressLine1"));
Log.p((String)obj.get("addressLine2"));
Log.p((String)obj.get("town"));
Log.p((String)obj.get("postcode"));
Log.p((String)obj.get("contactName"));
Log.p((String)obj.get("contactNumber"));
Log.p((String)obj.get("contactEmail"));
}
As you're using Codename One, parseJSON always returns a Map<String, Object>, but behaves differently when the root element is an array. In that case, the returned Map contains an object whose key is "root" which you then can iterate on to obtain the actual objects.
Map<String, Object> data = json.parseJSON(new InputStreamReader(
new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)data.get("root");
for(Map<String, Object> obj : content) {
Log.p(obj.getValue().toString());
}
For further info see the documentation for the parseJSON method.
You are getting an array of objects as it stats with [ and ends with ]. You have to try like this.
JSONArray jsonArr = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
for (int i = 0; i < jsonArr.length(); i++) {
String siteName = jsonArr.getJSONObject(i).getString("siteName");
System.out.println(siteName);
}

How to put array into Hashmap for encoding a JSON object

I'm trying to send API call using json-simple 1.1.1 and I save fields and values as a HashMap. I should send those parameters:
{ api_key : string,
product_id : string,
name : string,
tax_rates : array }
Here is a HashMap example:
HashMap<String,Object> arg = new HashMap<String, Object>();
arg.put("product_id","42");
arg.put("name", "EKOS");
arg.put("tax_rates", taxarray);
I saved taxarray as a HashMap as well:
HashMap<String, Object> taxarray = new HashMap<String, Object>();
taxarray.put("name","EKOS");
taxarray.put("type", "type_value_fixed");
taxarray.put("value", "56");
But when I execute an API call it reurns an error: Parameter 'tax_rates' is not valid. The required type of parameter is an array.
I had been trying to save taxarray HashMap as JSONArray as well. Could you please help me with this?
An additional question: how can I save 2 or more taxrates within one "tax_rates"? Here is an example:
HashMap<String,Object> arg = new HashMap<String, Object>();
arg.put("product_id","42");
arg.put("name", "EKOS");
arg.put("tax_rates", array [
taxarray1[],
taxarray2[]
]);
You should have something like this - Tax class:
public class Tax {
String name;
String type;
Integer[] values;
public Tax(String name, String type, Integer[] values) {
this.name = name;
this.type = type;
this.values = values;
}
}
And then use an array of objects of Tax class instead of HashMap for tax_rates : array.
This code using google json:
Map<String, Object> arg = new HashMap<String, Object>();
arg.put("product_id", "42");
arg.put("name", "EKOS");
arg.put("tax_rates",
new Tax[] { new Tax("EKOS", "type_value_fixed", new Integer[] { 1, 2, 3 }),
new Tax("ABC", "type_value_fixed", new Integer[] { 4, 5 }),
new Tax("DEF", "type_value_fixed", new Integer[] { 6, 7}) });
Gson gson = new Gson();
System.out.println(gson.toJson(arg));
Will give you such json:
{
"product_id": "42",
"name": "EKOS",
"tax_rates": [
{
"name": "EKOS",
"type": "type_value_fixed",
"values": [
1,
2,
3
]
},
{
"name": "ABC",
"type": "type_value_fixed",
"values": [
4,
5
]
},
{
"name": "DEF",
"type": "type_value_fixed",
"values": [
6,
7
]
}
]
}
tax_rates has to be an array, so do this:
List<Double> taxRates = new ArrayList<Double>();
taxRates.add(19);
taxRates.add(17.5);
Map<String,Object> arg = new HashMap<String, Object>();
arg.put("product_id","42");
arg.put("name", "EKOS");
arg.put("tax_rates", taxRates);

Java : Sort JSON String using key

I have a String which is in JSON format. I need to sort this JSON string using attributes but am unable to do it. JSON String is created by reading a CSV file. I do not want to read the CSV again and have to implement it using JSON String only. Is there a way to do that? Please let me know.
JSON String format is :
[
{
"address": "some address",
"name": "some name",
"phone": "some phone",
"age": "some age",
"SSN": "some SSN"
},
{
"address": "abc",
"name": "def",
"phone": "ghi",
"age": "jkl",
"SSN": "mno"
}
]
Please explain.
You can convert the JSONstring into a TreeMap with a Comparator you implement to compare by value, and then convert this TreeMap back to JSON.
See how to create a value Comparator here:
http://www.programcreek.com/2013/03/java-sort-map-by-value/
And then use ObjectMapper to convert the JSON into a map the the map back to JSON:
String json = "{\"address\" : \"def\","
+ "\"name\" : \"ghi\","
+ "\"phone\" : \"jkl\","
+ "\"age\" : \"def\","
+ "\"SSN\" : \"abc\"}";
Map<String, String> jsonMap = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
jsonMap = (mapper.readValue(json, Map.class));
Comparator<String> comparator = new ValueComparator(jsonMap);
Map<String, String> treeMap = new TreeMap<String, String>(comparator);
treeMap.putAll(jsonMap);
String sortedJson = mapper.writeValueAsString(treeMap);
System.out.println(sortedJson);
Result:
{"SSN":"abc","address":"def","name":"ghi","phone":"jkl"}
Comparator:
public class ValueComparator implements Comparator<String> {
Map<String, String> map = new HashMap<String, String>();
public ValueComparator(Map<String, String> map){
this.map = map;
}
#Override
public int compare(String s1, String s2) {
return map.get(s1).compareTo(map.get(s2));
}
}

Jackson: Cannot deserialize instance of object out of START_ARRAY

I'm getting this error when attempting to parse some JSON previously generated with Jackson. I generate the JSON like so
String ret = "";
ret = mapper.writeValueAsString(message.getPayload());
message.setPayload(ret);
Where message.getPayload() is a HashMap, in this instance containing two strings and a List of various objects. This creates the following malformed JSON
{
"user" : "john d example",
"items" : [ {
"val" : 99.5,
"id" : "phone",
"qty" : 1
}, {
"val" : 15.5,
"id" : "wine",
"qty" : 4
} ],
"address" : "123 example street"
}
Which throws an exception when examined thusly
Map<String, Object> ret = new HashMap<String, Object>();
String s = (String)message.getPayload();
ret = mapper.readValue(s, new TypeReference<Map<String, String>>(){});
How should I properly write this Map to JSON?
TypeReference<Map<String, String>> should be TypeReference<Map<String, Object>>. Jackson is attempting to parse the values as Strings rather than Lists because that is what it expects based on the TypeReference you passed in.

Categories

Resources