Parse array in JSON using JsonPath in Java - java

I am using jayway JsonPath library to parse the JSON using the path given. I am able to get the string value if I give the correct path. But I want to get the list of maps when I give the path if its an array. For example, I have a JSON like below:
{
"employees": {
"company": "Google",
"people": [{
"name": "John",
"age": 25,
"location": "zurich"
},
{
"name": "Peter",
"age": 27,
"location": "Lucerene"
}]
}
}
Below is the code I am using to parse the json.
if I give the path $.employees.people, I am getting the String, But I need to List of Maps. Below is the code I am using to Parse Json using jsonpath.
DocumentContext documentContext = JsonPath.parse(jsonStr);
JsonPath jsonPath = JsonPath.compile("$.employees.people");
List<Maps<String,String>> jsonList = documentContext.read(jsonPath) //But this is returning String
Anyone suggest proper approach to get what I expected.

try using,
DocumentContext documentContext = JsonPath.parse(jsonStr);
JsonPath jsonPath = JsonPath.compile("$.employees.people[?]");
List<Maps<String,String>> jsonList = documentContext.read(jsonPath);
if you need more details. readmore...

Related

How to convert nested Json in string into Json object in java

I am looking for some Java library, which can convert below give String into Json object.
Input: String reading from file.
{ "product": "{\"sku\":\"rtwre-rtwe\",\"price\":\"50.90\",\"currency_code\":\"SGD\",\"quantity\":1}", "is_organic": "0", "can_claim": "0", "t": "r", "device": "Phone", "amount_transactions": "0" }
Expected output: In some generic Java Json object.
{
"product": {
"sku": "rtwre-rtwe",
"price": "50.90",
"currency_code": "SGD",
"quantity": 1
},
"is_organic": "0",
"can_claim": "0",
"t": "r",
"device": "Phone",
"amount_transactions": "0"
}
Imp points: This is sample code, I have more dynamic json and don't have any Java object corresponding to my json. I can have string json in any key. It's not specific to particular key. I am looking for more generic code.
Here my goal if I read value of key "product" it should return Json instead of String. I want to read $.product.price using JsonPath library. http://jsonpath.com/
Edit1: I don't have much experience with Gson, Jackson and JsonObject libraries, but I tried whatever I could do. If you had handled the same scenario, please help me out.
To resolve it you can use :
JSONObject jsonObj = new JSONObject(myStringValue);
String myJsonStructureAsString = jsonObj.toString();
Where JSONObject is org.json.JSONObject form lib json-org.v2017.05.16.jar

java native JSON api for parsing

I've following JSON structure coming in,
{
"name": "product new",
"brand": {
"id": 1
},
"category": {
"id": 1
}
}
I can extract
jsonObject = Json.createReader(httpServletRequest.getInputStream()).readObject();
jsonObject.getString("name")
Errors:
jsonObject.getInt("brand.id")
jsonObject.getInt("category.id")
I'm using Java API for JSON.
Edit If I access
System.out.println(jsonObject.get("brand"));
// response {"id":1}
System.out.println(jsonObject.get("brand.id"));
// null
http://www.oracle.com/technetwork/articles/java/json-1973242.html
I don't think the API you're using supports nested expressions. You'll need to access the parent object, and then the specific field:
System.out.println(jsonObject.getJsonObject("brand").getInt("id"));
Or you can use an API that accepts a path expression, like Jackson:
JsonNode node = new ObjectMapper().readTree(httpServletRequest.getInputStream());
System.out.println(node.at("/brand/id").asInt());

how to iterate json on servlet

i have json like
{
"condition": "AND",
"rules": [{
"id": "BirthDate",
"field": "BirthDate",
"type": "date",
"input": "text",
"operator": "equal",
"value": "2016/04/13"
}]}
i just want to iterate it on servlet for that i create
public String getRuleList(){
String ruleList=this.get("rules");
return ruleList;
}
public String getcondition(){
return this.get("condition");
}
as getter setter when i send this json without using JSON.stringify i got the value of condition but unable to fetch rules.By using JSON.stringify i unable to fetch anything. please help..
rules is JSONArray and simple get returns an object. Try to get it with the json libraries custom method.
If you are using org.json try this
this.getJSONArray('rules')
Try to provide some more information such as the json library you are using, the output you got for this.get('rules') and how is this initialized for a much better answer
To solve above problem i do
result =JSON.stringify(result);
var json = JSON.parse(result);
var queryData={
rules:JSON.stringify(json.rules),
condition:JSON.stringify(json.condition)
};
console.log("result"+JSON.stringify(result));
if (!$.isEmptyObject(result)) {
var url = location.protocol + "//" + location.host +appContext+"?command=QueryBuilderServlet&action=getQueryJson";
$.ajax({
url:url,
type: "POST",
data:queryData,
dataType:'json',
});
thanks a lot for your help

unable to read key from json using JsonPath

I am trying to read a json value by providing json key.
code that i am tried. document is alreadt load it has above json.
i am using this link https://github.com/jayway/JsonPath
jsonPath = "$.Contact[?(#.key =~ /ContactID/i)].value";
Object attrValue = JsonPath.read(document, jsonPath);
"attrValue is empty". please guide me on this. thanks in advance
{
Date=/Date(1454410800000+1300)/,
Type=ACCREC,
Total=7000,
Status=PAID,
Contact={
Name=Abc,
Phones=[
],
Addresses=[
],
ContactID=df400dcd-6bdb-4cb5-98ce-496ec64c253f,
ContactGroups=[
],
ContactPersons=[
],
HasValidationErrors=false
},
DueDate=/Date(1454756400000+1300)/,
SubTotal=7000,
TotalTax=0,
AmountDue=0,
HasErrors=false,
InvoiceID=7aaa5fe5-25c3-47f9-b37f-f732b7705ee4
}

How to parse entrie json file into map in Java with Gson?

I have different jsons and don't want to create classes for each.
Is there a way to parse entire json file into Map?
For example:
{
"response": [
{
"id": 1,
"first_name": "Pavel",
"last_name": "Durov",
"screen_name": "durov",
"photo_200_orig": "https://pp.vk.me/c625129/v625129631/34d5e/BkAwjDyPg.jpg"
}
]}
And do like this:
Map map = Gson.fromJson(jsonString, Someclass.class);
long id = map.get("response").get(0).get("id");
Is there a way?

Categories