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);
Related
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.
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
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
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 3 years ago.
[
{
"boylam":31.8039,
"enlem":40.5906,
"il":"",
"ilPlaka":"",
"ilce":"",
"oncelik":0,
"yukseklik":2052,
"aciklama":"",
"modelId":124774,
"gps":0
}]
Hi I have such a JSON data in my hand. I had a hard time getting the data out of here. For example, how do I print the "boylam" option in JSON data?
You can use JSON.simple to convert string data to JSON objects. https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1
public static void main(String[] args) throws ParseException {
String data = "[\n" +
"{\n" +
" \"boylam\":31.8039,\n" +
" \"enlem\":40.5906,\n" +
" \"il\":\"\",\n" +
" \"ilPlaka\":\"\",\n" +
" \"ilce\":\"\",\n" +
" \"oncelik\":0,\n" +
" \"yukseklik\":2052,\n" +
" \"aciklama\":\"\",\n" +
" \"modelId\":124774,\n" +
" \"gps\":0\n" +
"}]";
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(data);
JSONObject jsonObject = (JSONObject) jsonArray.get(0);
System.out.println(jsonObject.get("boylam"));
}
Use Google Gson,the code maybe like this:
// construct the json object
JsonArray jsonArray = new JsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("boylam",31.8039);
jsonArray.add(jsonObject);
// iterate the json array
jsonArray.forEach(jsonElement -> {
JsonObject element = (JsonObject) jsonElement;
System.out.println(element.get("boylam"));
});
using com.google.gson.Gson class, you can do this.
Gson gson= new Gson();
JSONObject json=new JSONObject();
json.put("boylam", "31.8039"); // this is your json object
Map map=gson.fromJson(json.toString(), Map.class);
System.out.println(map.get("boylam")); //ouput 31.8039
Im using GSON to parse this JSON file:
{
"database" : {
"source" : "google",
"items" : [
{"title" : "hello world",
"id" : "id_hello_world"},
{"title" : "goodbye world",
"id" : "id_goodbye_world"}
]
}
}
Which ive read into String jsonLine
Im trying to parse it and output all the values but im getting a ClassCastException at the
JsonObject source = database.getAsJsonObject("source") line.
I think im searching for the data wrong. Im using this to search and output:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = (JsonObject) jelement;
JsonObject database = jobject.getAsJsonObject("database"); //Get Database
JsonObject source = database.getAsJsonObject("source"); //Get Source
System.out.println("Source: " + source.toString()); //Print source
JsonArray items = database.getAsJsonArray("items"); //Get items array
for(int i=0; i< items.size(); i++){ //for every item
JsonObject item = (JsonObject) items.get(i); //Select item i
JsonObject title = (JsonObject) item.getAsJsonObject("title");
JsonObject id = (JsonObject) item.getAsJsonObject("id");
System.out.println("Item " + i + " title : " + title.toString() + ", id : " + id.toString());
}
If someone could correct my code that would be perfect. I know there are other simpler ways to do this using GSON.fromJSON(jsonLine, Wrapper.class) but im trying to learn to do it this way too. Thanks for the help!
Before you are going to use Gson method, create your template structure:
class Item{
private String item = "";
private String id = ""; // for sure you can use 'int'
}
public class DataBase{
private List<Item> items = null;
private String source = "";
}
Now your main class:
public class YourClass{
private DataBase database = "";
....
database = gson.fromJson(yourString, YourClass.class);
...
}
Don't forget try/catch wrapper
Enjoy
use JsonPrimitive instead of JsonObject. (it must be internal bug of GSON, because, trying to convert JsonPrimitive to JsonObject was impossible, as far as the version of GSON 2.2.3)
So, your code comes like this:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = (JsonObject) jelement;
JsonObject database = jobject.getAsJsonObject("database"); // Get
// Database
JsonPrimitive source = database.getAsJsonPrimitive("source"); // Get
// Source
System.out.println("Source: " + source.toString()); // Print source
JsonArray items = database.getAsJsonArray("items"); // Get items array
for (int i = 0; i < items.size(); i++) { // for every item
JsonObject item = (JsonObject) items.get(i); // Select item i
JsonPrimitive title = item.getAsJsonPrimitive("title");
JsonPrimitive id = item.getAsJsonPrimitive("id");
System.out.println("Item " + i + " title : " + title.toString()
+ ", id : " + id.toString());
}
As Maxim Shoustin showed, creating template will be good solution for it.