JSONObject["featured_image"] is not a String - java

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

Related

JSONPath: Get root array object using filter of child value

Im trying to get JSONPath expression to filter my JSON and get whole sport object using value of child array.
I have following JSON:
[{
"name": "Soccer",
"regions": [{
"name": "Australia",
"leagues": [{
"name": "Australia league",
"inplay": 5,
}
]
}
]
}, {
"name": "Tennis",
"regions": [{
"name": "Germany",
"leagues": [{
"name": "Germany league",
"inplay": 0,
}
]
}
]
}
]
I need to get whole sport object where "inplay == 0" using JsonPath expression.
Result should look like that:
{
"name": "Tennis",
"regions": [{
"name": "Germany",
"leagues": [{
"name": "Germany league",
"inplay": 0,
}
]
}
]
}
Regions and Leagues count can be > 1
Therefore $[?(#.regions[0].leagues[0].inplay == 0)] is not suitable
Tried $[?(#.regions[*].leagues[*].inplay == 0)] but it doesnt work
This works for me
$[?(#.regions[0].leagues[0].inplay == 0)]
Since this is not directly supported (as of now) in JayWay JSONPath we leverage contains as a workaround:
$[?(#.regions..inplay contains '0')]
Note: It may look like contains would work similar to a 'like' operator or instr function but this is not the case here. If the inplay value contains a 0, e.g. 10 it would not pull the record (according to my tests;)

Jackson/Gson get specified key from Json - 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?

Add data from Api response into Firebase Database in Android

This I want to add data to firebase database through Volley API response in Android.
"data": [{
"id": 1,
"full_name": "abc",
"email": "abc999#gmail.com",
"country_code": "+91",
"phone": 2147483647,
"profile_pic": "",
"type": 0,
"status": 1,
"reset_token": "",
"verify_token": "$2y$10$YXCZ1yteimLatQnAszJTi.HOGDZrr9xjKJtIDNs3uagX3elFUlC.2",
"created_at": "2019-05-07 07:53:29",
"updated_at": "2019-05-08 12:57:45",
"deleted_at": null
}, {
"id": 2,
"full_name": "xyz",
"email": "xyz#gm.com",
"country_code": "+91",
"phone": 2147483647,
"profile_pic": "",
"type": 0,
"status": 1,
"reset_token": null,
"verify_token": "$2y$10$Dtk.BdqBgHFyGcpj9bHyI.JRPJlc90Qmhxx0Imm0Mzzd3x6QchDMi",
"created_at": "2019-05-07 08:34:39",
"updated_at": "2019-05-07 08:34:39",
"deleted_at": null
}, {
"id": 3,
"full_name": "abc",
"email": "abc#gmail.com",
"country_code": "091",
"phone": 123456,
"profile_pic": "",
"type": 0,
"status": 1,
"reset_token": "$2y$10$mT9MqON6gMre0rKtoK0ON.VApZYBZP0PY55uM017Cz74E69qBILjm",
"verify_token": "$2y$10$HMBteSyYTKZ3XgYviUdNORKOw1Bpan5m0UcqIyx3dZrYUsNajou",
"created_at": "2019-05-07 08:47:29",
"updated_at": "2019-05-17 05:55:00",
"deleted_at": null
}
]
Now I want firebase data should look like this
firebasedemo
.
+ Users
.
. . name:"abc"
I am writing this line in Api call For loop
Rootref= FirebaseDatabase.getInstance().getReference();
Rootref.child("Users").child("name").setValue(name);
But I am getting only one record in firebase not all
Any help will be highly appreciated
Try the following:
DatabaseReference rootref = FirebaseDatabase.getInstance().getReference();
rootref.child("Users").push().setValue(name);
From the docs:
public DatabaseReference push ()
Create a reference to an auto-generated child location. The child key is generated client-side and incorporates an estimate of the server's time for sorting purposes. Locations generated on a single client will be sorted in the order that they are created, and will be sorted approximately in order across all clients.

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.

How can I send this params (parent,level,expanded,isLeaf) to server in jqGrid Tree Grid?

I can't send this params to server using jqTreeGrid and Java with Struts2:
level
parent
isLeaf
expanded
I have created a jqGrid TreeGrid using this documentation treegrid
This is my code:
jQuery("#treegrid2").jqGrid({
treeGrid: true,
treeGridModel : 'adjacency',
ExpandColumn : 'name',
url: './getTaskManagement.action',
editurl:'./sendActions.action',
datatype: "json",
jsonReader: {root: "listTask", repeatitems: false},
mtype: "POST",
colNames:["id","Task Division","PM", "Risk", "Duration","Start Date","End Date","NR","Comments","Parent","isLeaf","Level","Expanded"],
colModel:[
{name:'id',index:'id', width:1,hidden:true,key:true,editable:true},
{name:'name',index:'name', width:420,editable:true},
{name:'pm',index:'pm', width:80, align:"center",editable:true},
{name:'risk',index:'risk', width:60, align:"center",editable:true},
{name:'duration',index:'duration', width:80, align:"right",editable:true},
{name:'begin',index:'begin', width:80,align:"right",editable:true},
{name:'end',index:'end', width:80,align:"right",editable:true},
{name:'nr',index:'nr', width:80,align:"right",editable:true},
{name:'comments',index:'comments', width:170,align:"center",editable:true},
{name:'parent',index:'parent',hidden:true,editable:true},
{name:'isLeaf',index:'isLeaf',hidden:true,editable:true},
{name:'level',index:'level',hidden:true,editable:true},
{name:'expanded',index:'expanded',hidden:true,editable:true}
],
height:'auto',
viewrecords : true,
multiselect : true,
multiboxonly : true,
pager : "#ptreegrid2",
caption: "Example TreeGrid"
});
and this is the json result from server:
{
"actions": "success",
"rows": [
{
"begin": "2014-01-27",
"comments": "Some comments",
"duration": 20,
"end": "2014-02-17",
"expanded": "false",
"id": 1,
"isLeaf": "false",
"level": "0",
"name": "<b>A.Project Launch</b>",
"nr": "Some NR",
"parent": "",
"pm": "Some pm",
"risk": "Some risk"
},
{
"begin": "2014-01-27",
"comments": "Some comments",
"duration": 2,
"end": "2014-01-29",
"expanded": "false",
"id": 2,
"isLeaf": "true",
"level": "1",
"name": "Reverse SAMIR (if necessary): review what is in production",
"nr": "Some NR",
"parent": "1",
"pm": "Some pm",
"risk": "Some risk"
}
]
}
When I Try to edit a record using jqGrid pager I can send all params from colModel, except level, parent, isLeaf and expanded.
Request Header Form data:
id:1
name:A.Project Launch
pm:Some pm
risk:Some risk
duration:20
begin:2014-01-27
end:2014-02-17
nr:Some NR
comments:Some comments
oper:edit
and when I try to add new record send these params to server:
id:
name:a
pm:b
risk:c
duration:1
begin:e
end:f
nr:g
comments:h
parent:
oper:add
However never sends the other params (level,isLeaf,Expnaded), I need the params beacause I want to save an object with Java in database. so If these params are null obviusly in database are null too.
When I Try to retrieve the json data again (level,isLeaf,Expnaded,parent) are null and jqGrid TreeGrid don't respect the format because need these params for build correctly the Tree Grid.
Does somebody have an idea to solve this?
thanks and regards!!

Categories