Jackson/Gson get specified key from Json - Java - java

i have problem with get specified value from json. I need get Key value from json below, its start with array/list.
[
{
"Version": 1,
"Key": "353333_PC",
"Type": "PostalCode",
"Rank": 500,
"LocalizedName": "Suwalki",
"EnglishName": "Suwalki",
"PrimaryPostalCode": "16-400",
"Region": {
"ID": "EUR",
"LocalizedName": "Europe",
"EnglishName": "Europe"
},
"Country": {
"ID": "PL",
"LocalizedName": "Poland",
"EnglishName": "Poland"
}
}
]
I have tried code like this:
String content = parent.path("Key").asText();
return content;
but it returns empty string. Have u any idea how get this?

Related

How to get json key values by another key value

I have a JSON output like this:
{
"items": [
{
"id": "1",
"name": "Anna",
"values": [
{
"code": "Latin",
"grade": 1
},
{
"code": "Maths",
"grade": 5
}
]
},
{
"id": "2",
"name": "Mark",
"values": [
{
"code": "Latin",
"grade": 5
},
{
"code": "Maths",
"grade": 5
}
]
}
]
}
I need to get field values for "name": "Anna". I am getting RestAssured Response and would like to use my beans to do that, but I can also use jsonPath() or jsonObject(), but I don't know how. I searched many topics but did not find anything.

Parse json response of rest API and delete certain jsonObjects - JAVA

I have a json file as below which I am getting as a response from rest API:
{
"label": " MARA LEYZIN",
"ClassCode": "PROFESSIONAL",
"actvFlg": "A",
"name": "MARA LEYZIN",
"Typ": {
"label": "C_TYP_LU",
"TypCode": "PROFESSIONAL "
},
"Address": {
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item": [
{
"label": "Address",
"addrTypFk": {
"label": "C_ADDRESS_TYPE_LU",
"addrTypCd": "INDUSTRY",
"addrTypDesc": "Industry"
}
}
]
}
I am trying to parse this in Java and to remove some unwanted json objects. Like I want the following string to be replaced by blank:
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item":
To achieve this I am trying the following approach:
String jsonStr = new String(Files.readAllBytes(Paths.get(inputFile)));
System.out.println(jsonStr);
jsonStr.replaceAll("link", "");
But it is not replacing the required string with blanks. Please help me in this.
string object is immutable , so basically if do you want to replace something
System.out.println(jsonStr.replaceAll("link", "")); this will print the replaced string but it will not affect the original string, however if you do this
jsonStr=jsonStr.replaceAll("link", "");
System.out.println(jsonStr); this will print the replaced string
First of all:
Your JSON is not validate. You're missing a closing curly bracket at the end of it.
{
"label": " MARA LEYZIN",
"ClassCode": "PROFESSIONAL",
"actvFlg": "A",
"name": "MARA LEYZIN",
"Typ": {
"label": "C_TYP_LU",
"TypCode": "PROFESSIONAL "
},
"Address": {
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item": [{
"label": "Address",
"addrTypFk": {
"label": "C_ADDRESS_TYPE_LU",
"addrTypCd": "INDUSTRY",
"addrTypDesc": "Industry"
}
}]
}
}
Second of all you should just change order of your commands to this:
jsonStr.replaceAll("link", "");
System.out.println(jsonStr);
Important addition:
And I would suggest you to use org.json library or even better JACKSON to parse JSON files.
Here's tutorial how to use jackson and it's my warmest suggestion.
You will save a lot of time and you can do whatever you like.

JSONObject["featured_image"] is not a String

Hi all I am getting a following json from Wordpress rest APi Call
[
{
"ID": 248,
"post_title": "test post",
"post_author": "admin",
"excerpt": "",
"url": "http://localhost/wp-learning/?p=248",
"permalink": "http://192.168.10.31/wp-learning/test-post/",
"post_date": "2017-08-07 09:15:57",
"comment_count": "2",
"category": [
{
"term_id": 1,
"name": "Uncategorized",
"slug": "uncategorized",
"term_group": 0,
"term_taxonomy_id": 1,
"taxonomy": "category",
"description": "",
"parent": 0,
"count": 1,
"filter": "raw",
"cat_ID": 1,
"category_count": 1,
"category_description": "",
"cat_name": "Uncategorized",
"category_nicename": "uncategorized",
"category_parent": 0
}
],
"views": "4",
"featured_image": false
},
{
"ID": 247,
"post_title": "The Coolest Vanity Apps for You and Your Girls",
"post_author": "admin",
"excerpt": "",
"url": "http://td_uid_79_598817d2cebf2",
"permalink": "http://192.168.10.31/wp-learning/the-coolest-vanity-apps-for-you-and-your-girls/",
"post_date": "2017-08-07 07:33:38",
"comment_count": "0",
"category": [
{
"term_id": 15,
"name": "Beauty",
"slug": "beauty",
"term_group": 0,
"term_taxonomy_id": 15,
"taxonomy": "category",
"description": "On each category you can set a Category template style, a Top post style (grids) and a module type for article listing.",
"parent": 14,
"count": 17,
"filter": "raw",
"cat_ID": 15,
"category_count": 17,
"category_description": "On each category you can set a Category template style, a Top post style (grids) and a module type for article listing.",
"cat_name": "Beauty",
"category_nicename": "beauty",
"category_parent": 14
}
],
"views": "0",
"featured_image": "http://192.168.10.31/wp-learning/wp-content/uploads/2017/08/3.jpg"
}
]
I am problem in fetching the tag name "featured_image". what type of datatype is it? i tried
jsonObj.getString("featured_image");
for this it gave me error JSONObject["featured_image"] is not a String.
also
resultsObj.getJSONObject("featured_image").toString()
for this it gave me error JSONObject["featured_image"] is not a JSONObject.
You are doing resultsObj.getJSONObject("featured_image").toString() which asks to get a JSON Object out of the Key/Value at 'featured_image'.
But we can see that the value is a string, or a bool:
"featured_image": "http://192.168.10.31/wp-learning/wp-content/uploads/2017/08/3.jpg"
"featured_image": false
So you should not call getJSONObject() on this key, at all.
Based on your JSON Structure, it looks like the "featured_image" is of boolean type, it is not string or object.
I think its inner json problem
try like this :
JSONObject category = jsonObj.getJSONObject("category");
category.getJSONObject("featured_image");
You can use following code, I didn't tested but that can be helpful in determining the data type and based on the type you can decide which method needs to be called.
So use:
JsonValue type = resultsObj.get("featured_image").getValueType();
if (type.getValueType() == JsonValue.ValueType.TRUE || type.getValueType() == JsonValue.ValueType.FALSE){
// call boolean method
boolean bValue = resultsObj.get("featured_image").getAsBoolean()
}else{
//based on you type you can call respective method.
}
Refer following link:
JsonValueType
getValueType

How to index a Json object with object and its reference in elasticsearch?

I am working with Elasticsearch recently, and I meet a problem that don't know how to solve it.
I have a Json like:
{
"objects": [
"object1": {
"id" : "12345",
"name":"abc"
},
"12345"
]
}
Object2 is a reference of object1, when I trying to saving(or called indexing) into elastic search, it says:
"org.elasticsearch.index.mapper.MapperParsingException: failed to parse"
After I google I found that because object1 is an object, but object 2 is considered as a string.
We cannot change our json in our project, so in this case how can I save it in the elasticsearch?
Thanks for any help and suggestion.
How do you do that?
I run this command and it works.
PUT test/t1/1
{
"objects": {
"object1": {
"id" : "12345",
"name":"abc"
},
"object2": "12345"
}
}
and the result is:
{
"_index": "test",
"_type": "t1",
"_id": "1",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 2,
"failed": 0
},
"created": true
}
UPDATE 1
Depending on your requirements one of these may solve your problem:
PUT test/t1/2
{
"objects": [
{
"object1": {
"id": "12345",
"name": "abc"
}
},
{
"object2": "12345"
}
]
}
PUT test/t1/2
{
"objects": [
{
"object1": {
"id": "12345",
"name": "abc"
},
"object2": "12345"
},
{
...
}
]
}

Checking Keys in JSON Records using Java

"transaction": {
"id": 1,
"empid": "12345",
"details1": {
"name": "xyz",
"age": "30",
"sex": "M",
"Address": {
"Office": "office",
"Home": "Home"
}
},
"abcDetails": "asdf",
"mobile": 123455
},
I need to test if JSON record contains more then two keys(details, Address).
Then, I need to pass those key input to this line:
parserValue1 = parserValue.asObject().get("firstKey").asObject().get("secondKey");
Can anyone help me?
Many json parsers have a has("key") or contains("key") accessor.
Otherwise you will have to add a condition to check if get("") returns null, or turn your whole Json object into a map, where you do the same checks.

Categories