Java Extract key values from nested json - java

i do have following JSON and i am trying to extract objects inside result
{
"status":true,
"results":{
"type1":{
"id":"type1"
},
"type2":{
"id":"type2"
}
}
}
Desired output is
type1,type2
I am using Gson for serialization and deserialization.

These are the steps you should be doing when using gson
get keys of the json objects which are inside "results" alone
get it as json object which has keys and values
collect the entry set our of the JSON
create an iterator so that later you can extract the keys
Here is code that does the same job:
public static void main(String[] args) throws Exception {
String json = "{\r\n" +
" \"status\":true,\r\n" +
" \"results\":{\r\n" +
" \"type1\":{\r\n" +
" \"id\":\"type1\"\r\n" +
" },\r\n" +
" \"type2\":{\r\n" +
" \"id\":\"type2\"\r\n" +
" }\r\n" +
" }\r\n" +
"}";
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(json).getAsJsonObject();
//get keys of the json objects which are inside "results" alone
//get it as json object which has keys and values
//collect the entry set our of the JSON
//create an iterator so that later you can extract the keys
Iterator<Entry<String, JsonElement>> iterator = obj.get("results")
.getAsJsonObject()
.entrySet()
.iterator();
while(iterator.hasNext()) {
//here you will get the keys like - type1 and type2
System.out.println(iterator.next().getKey());
}
}
Code Edit: What #fluffy pointed makes complete sense. Made the change

Related

How to find the tag Value in the dynamic JSON-Object with Java 8

I have JSON-object which has a dynamic key inside it. I need to get a specific value mapped to this dynamic Key.
For example: value "10.00" will be returned for the key "value" and value REFUND_COMPLETED will be obtained as a result for the key "refundState"
Code:
public static void main(String[] args) {
String json2 = "{\n"
+ " \"refundStatusDetails\": {\n"
+ " \"txn_f2a7802c-ef84-43c3-8615-5f706b995c23\": {\n"
+ " \"refundTransactionId\": \"txn_f2a7802c-ef84-43c3-8615-5f706b995c23\",\n"
+ " \"requestId\": \"refund-request-id-1\",\n"
+ " \"refundState\": \"REFUND_COMPLETED\",\n"
+ " \"amount\": {\n"
+ " \"currency\": \"INR\",\n"
+ " \"value\": \"10.00\"\n"
+ " },\n"
+ " \"refundRequestedTime\": 1513788119505,\n"
+ "}";
System.out.println("JSON: " + json2);
JsonParser p = new JsonParser();
Map<String,String> res =check("refundState", p.parse(json2));
System.out.println("JSON: " + res.get("refundState"));
}
private static Map<String,String> check(String key, JsonElement jsonElement) {
Map<String,String> res = new HashMap<>();
if (jsonElement.isJsonObject()) {
Set<Map.Entry<String, JsonElement>> entrySet = jsonElement.getAsJsonObject().entrySet();
entrySet.stream().forEach((x) ->{
if (x.getKey().equals(key)) {
res.put(x.getKey(),x.getValue().toString());
}
});
}
return res;
}
If you are interested to access any field in a JSON object structure then you can use a method like the following one that I used to access the fields that I needed from an JSON Array structure using "package org.json;"
public static final String COLLECTION_OBJECT = "collectionObject";
public static final String FIELD = "field";
private ArrayList<Object> getSearchFilterCriteriaAsString() {
String jsonString = "{" +
"\n\"collectionObject\": " +
"[\n" +
"{" +
"\n\"field\": \"productId\"," +
"\n\"value\": \"3\"," +
"\n\"operator\": \"EQUALS\"\n" +
"},\n" +
"{" +
"\n\"field\": \"productPrice\"," +
"\n\"value\": \"15\"," +
"\n\"operator\": \"MORE_THAN\"\n" +
"},\n" +
"{" +
"\n\"field\": \"productQuantity\"," +
"\n\"value\": \"25\"," +
"\n\"operator\": \"LESS_THAN\"\n" +
"}\n" +
"]\n" +
"}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(COLLECTION_OBJECT);
ArrayList<Object> filteredObjectsList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject filteredObj = (JSONObject) jsonArray.get(i);
filteredObjectsList.add(filteredObj.getString(FIELD));
}
}
return filteredObjectsList;
}
As long as you know your key values you can parse any JSON as deep you want, without to care about how big it is, how many attributes it has.
I have JSON Object which has a dynamic key inside the object I need a
specific key value
The recursive method listed below is capable of fetching the value mapped to the provided key from a nested JSON-object.
The method return an optional result.
If provided JsonElement is not a JsonObject an empty optional will be returned.
Otherwise, if the given JSON-object contains the given key the corresponding value wrapped by an optional will be returned. Or if it's not the case the entry set obtained from an object will be processed with stream. And for every JSON-object in the stream method getValue() will be called recursively.
If the given key is present in one of the nested objects, the first encountered non-empty optional will be returned. Or empty optional if the key was not found.
private static Optional<JsonElement> getValue(String key, JsonElement jsonElement) {
if (!jsonElement.isJsonObject()) {
return Optional.empty();
}
JsonObject source = jsonElement.getAsJsonObject();
return source.has(key) ? Optional.of(source.get(key)) :
source.entrySet().stream()
.map(Map.Entry::getValue)
.filter(JsonElement::isJsonObject)
.map(element -> getValue(key, element))
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());
}
main() - demo
public static void main(String[] args) {
String json2 =
"""
{
"refundStatusDetails": {
"txn_f2a7802c-ef84-43c3-8615-5f706b995c23": {
"refundTransactionId": "txn_f2a7802c-ef84-43c3-8615-5f706b995c23",
"requestId": "refund-request-id-1",
"refundState": "REFUND_COMPLETED",
"amount": {
"currency": "INR",
"value": "10.00"
},
"refundRequestedTime": "1513788119505"
}
}
}""";
JsonElement element = JsonParser.parseString(json2);
System.out.println(getValue("refundState", element));
System.out.println(getValue("value", element));
}
Output
Optional["REFUND_COMPLETED"]
Optional["10.00"]
Note:
If you are using Java 17 you can utilize text blocks by plasing the text between the triple quotation marks """ JSON """.
Constructor of the JsonParser is deprecated. Instead of instantiating this class, we have to use its static methods.

parse strange Json response to a list

I want to parse this object to a list of string. I do not need the key but just want the value as a list of string.
I cannot have a simple model classes because the keys object are more than 1000 in some responses and are random.
So please any idea how to parse it to list in kotlin or java?
{
"data": {
"21": "593754434425",
"22": "4560864343802",
"23": "7557134347529",
"24": "5937544344255",
"25": "45608643438024",
"26": "75571343475293"
}
}
You could first deserialize it as it is, and then convert to a list.
The JSON can be represented this way:
data class Response(val data: Map<String, String>)
You can mark this class #Serializable and use Kotlinx Serialization to deserialize it, or you can use other libraries like Moshi or Jackson (with jackson-module-kotlin).
Once it's deserialized, simply get the values of the map (it's a collection):
val response = Json.decodeFromString<Response>(yourJsonString)
// this is a Collection, not List, but it should be good enough
val stringValues = response.data.values
// if you really need a List<String>
val list = stringValues.toList()
If you want to get the values in the natural order of the keys, you can also use something like:
val values = response.data.toSortedMap(compareBy<String> { it.toInt() }).values
You can use this to parse your data:
val it: Iterator<String> = json.keys()
val arrayList = ArrayList<String>()
while (it.hasNext()) {
val key = it.next()
arrayList.add(json.get(key))
}
A better way is to change the json model, if you access it.
{
"data": [
"593754434425","4560864343802",
"7557134347529","5937544344255",
"45608643438024","75571343475293"
]
}
For this problem, its handy to use the libriary org.json.
See following code snippet:
import org.json.JSONObject;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Defining the input
String input = "{\n" +
" \"data\": {\n" +
" \"21\": \"593754434425\",\n" +
" \"22\": \"4560864343802\",\n" +
" \"23\": \"7557134347529\",\n" +
" \"24\": \"5937544344255\",\n" +
" \"25\": \"45608643438024\",\n" +
" \"26\": \"75571343475293\"\n" +
" }\n" +
"}\n";
// Parsing it to a json object with org.json
JSONObject inputJson = new JSONObject(input);
// If inputJson does not contain the key data, we return
if(!inputJson.has("data")) return;
// Else we read this data object to a new JSONObject
JSONObject dataJson = inputJson.getJSONObject("data");
// Define an array list where all the values will be contained
ArrayList<String> values = new ArrayList<>();
// Get a key set of the dat json object. For each key we get its respective value and add it to our value array list
for (String key : dataJson.keySet()) values.add(dataJson.getString(key));
// Print all values
for (String value : values) System.out.println(value);
}
}
=>
4560864343802
7557134347529
5937544344255
45608643438024
75571343475293
593754434425
Installing org.json is the easiest with a package manager like maven or gradle.
Guys i have comeup with a similar solution for the problem here
this is my model class
data class UnVerifiedTagIds(
#SerializedName("data")
val data: Object
)
and this is how i parse the respone here
val values: ArrayList<String> = ArrayList()
val list_of_tag_ids: ArrayList<String> =response.data as ArrayList<String>
The ist one is the dataclass for the response
and the 2nd one is the ApiCallInterface m using Retrofit...
and the last one is the apicall itself
I am using Kotlin language
do class name with name like this data class Result(val data:Map<String,String>)
and using library GSON for convert string json to this model
val json = "{\n" +
" \"data\": {\n" +
" \"21\": \"593754434425\",\n" +
" \"22\": \"4560864343802\",\n" +
" \"23\": \"7557134347529\",\n" +
" \"24\": \"5937544344255\",\n" +
" \"25\": \"45608643438024\",\n" +
" \"26\": \"75571343475293\"\n" +
" }\n" +
"}"
val dat = Gson().fromJson(json,Result::class.java)
if (dat.data.isNotEmpty()){
val list= dat.data.values.toMutableList()
print(list)
}
that works fine with me

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.

extract a json node from the json

how to extract a json node from another json .for example I want to fetch the "Company Name" i.e "kjh".But using this json parser code I am able to fetch the whole json and not only comapnt name..Can somebody help
jsonObject = (JSONObject) new org.json.simple.parser.JSONParser().parse(domainRequest);
final String companyName = (String) jsonObject.get("companyName");
here is the Json content:
{"companyName":{"Company Name:":"kjh","Address 1:":"kjhhkh","Address 2:":"hkjhkj","Address 3:":"hkjhhkj","Address 4:":"kjhj","Postcode:":898,"Default Email Address:":"kkjkh#y","Company Registration No:":98,"VAT No:":89098,"Website":"http://localhost:9000/#/support/domain/request?formLinkUuid=7f000101-4fdf-160d-814f-dfa60dc80000"}}
{"companyName" : {
"Company Name:":"kjh",
"Address 1:":"kjhhkh",
"Address 2:":"hkjhkj",
"Address 3:":"hkjhhkj",
"Address 4:":"kjhj",
"Postcode:":898,
"Default Email Address:":"kkjkh#y","Company Registration No:":98,
"VAT No:":89098,
"Website":"http://localhost:9000/#/support/domain/request?formLinkUuid=7f000101-4fdf-160d-814f-dfa60dc80000"
}}
You missed 1 step, you are actually getting a map (key-value pair), using this map get company name
public static void main(String[] args) throws JSONException {
String domainRequest = "{\"companyName\":{\"Company Name:\":\"kjh\",\"Address 1:\":\"kjhhkh\",\"Address 2:\":\"hkjhkj\",\"Address 3:\":\"hkjhhkj\",\"Address 4:\":\"kjhj\",\"Postcode:\":898,\"Default Email Address:\":\"kkjkh#y\",\"Company Registration No:\":98,\"VAT No:\":89098,\"Website\":\"http://localhost:9000/#/support/domain/request?formLinkUuid=7f000101-4fdf-160d-814f-dfa60dc80000\"}}";
JSONObject jsonObject = new JSONObject(domainRequest);
JSONObject jsonMap = (JSONObject) jsonObject.get("companyName"); // Generates HashMap, key-value pair
String companyName = (String) jsonMap.get("Company Name:"); // from map prepared above get key value
System.out.println(companyName);
}
Output
kjh
It is weird your json format. You should be check it out.
Remove colon from children property name.
String json =
"{\"companyName\" : {\n" +
" \"Company Name:\":\"kjh\",\n" +
" \"Address 1:\":\"kjhhkh\",\n" +
" \"Address 2:\":\"hkjhkj\",\n" +
" \"Address 3:\":\"hkjhhkj\",\n" +
" \"Address 4:\":\"kjhj\",\n" +
" \"Postcode:\":898,\n" +
" \"Default Email Address:\":\"kkjkh#y\",\"Company Registration No:\":98,\n" +
" \"VAT No:\":89098,\n" +
" \"Website\":\"http://localhost:9000/#/support/domain/request?formLinkUuid=7f000101-4fdf-160d-814f-dfa60dc80000\"\n" +
" }}";
JsonElement jsonElement = new Gson().fromJson(json, JsonElement.class);
String companyName = jsonElement.getAsJsonObject().get("companyName").getAsJsonObject().get("Company Name:").getAsString();
System.out.println(companyName);

Parsing JSON in Java Play

I have a simple JSON object I wish to parse in Play, I am currently trying the following but having no luck:
HashMap<String,Object> result = new ObjectMapper().readValue(stringBuilder.toString(), HashMap.class);
My JSON Object looks like the following:
[{"id":"537b4f2e30047c51863094dd","from":"jacob","to":"duncan","subject":"Welcome to the message system!","message":"Hello World"},{"id":"537bb23930044f26cfd24464","from":"jacob","to":"duncan","subject":"Welcome to the message system!","message":"Hello World"}]
Can anybody provide an example on how to parse and iterate over this?
Play 2 uses Jackson API for JSON, so you should use it
Sample:
String jsonString = "[{\"id\":\"537b4f2e30047c51863094dd\",\"from\":\"jacob\",\"to\":\"duncan\",\"subject\":\"Welcome to the message system!\",\"message\":\"Hello World\"},{\"id\":\"537bb23930044f26cfd24464\",\"from\":\"jacob\",\"to\":\"duncan\",\"subject\":\"Welcome to the message system!\",\"message\":\"Hello World\"}]";
JsonNode node = Json.parse(jsonString);
if (node.isArray()) {
Iterator<JsonNode> elements = node.elements();
while (elements.hasNext()) {
JsonNode obj = elements.next();
debug(
"Message with ID: " + obj.get("id")
+ " from: " + obj.get("from")
+ " to: " + obj.get("to")
+ " subject: " + obj.get("subject")
+ " message: " + obj.get("message")
);
}
}
Tip: It was refactored some time ago, so depending on used Play version check Codehaus Jackson or FasterXML Jackson APIs
It looks like you've got a list, where each entry is a map key value pairs.
You can use a standard json parser to convert it into an object like this:
String json = "[{\"id\":\"537b4f2e30047c51863094dd\",\"from\":\"jacob\",\"to\":\"duncan\",\"subject\":\"Welcome to the message system!\",\"message\":\"Hello World\"},{\"id\":\"537bb23930044f26cfd24464\",\"from\":\"jacob\",\"to\":\"duncan\",\"subject\":\"Welcome to the message system!\",\"message\":\"Hello World\"}]";
Type listType = new TypeToken<List<Map<String, Object>>>(){}.getType();
List<Map<String, Object>> data = new Gson().fromJson(json, listType);
Then you can iterate over the List and each Map as normal:
for (Map<String, Object> map : data) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
// do stuff
}
}
P.S.
It looks like all your value data is also in String form, so you might want to consider making a Map<String, String> instead of Map<String, Object> if that's actually the case.

Categories