Using the java json path library: https://github.com/json-path/JsonPath
Given a json like this
{
"store": {
"book": [
{
"category": "reference"
},
{
"category": "fiction"
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
I would like to return "book" as a list of strings. For examples:
List<String> results = JsonPath.read(example, "$.store.book[*]");
And results should look like:
["{\"category\":\"reference\"}", "{\"category\":\"fiction\"}"]
Is there a way to achieve this?
Currently:
System.out.println(udf.jsonExtractScalar(testExample, "$.store.book[*]").getClass().getName());
--> net.minidev.json.JSONArray
As book is a JsonArray in you json tree, you can use JsonArray type and retrieve the data from it and add to the list.
Here is an example.
JSONArray jsonArray = new JSONArray(jsonArrayString);
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
Replace jsonArrayString with you jsondata's books array name and you will be good to go.
The class used will be JSONArray class which is
`org.json.JSONArray`
Related
I am working on updating functional test suites using Cucumber feature file.The issue my output is an array which is not sorted.Index of the object may change.
Array:
[{
"id": "12",
"name": "Something"
},
{
"id": "13",
"name": "Another Something"
}
]
Here I wanna assert name when Id=13 only.Any help would be appreciated.
The Json is list of objects within an Array so you need parse them and validate the each Object. You can do like below,
Code:
JSONArray jsonArray = new JSONArray(JsonAsString);
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = new JSONObject(jsonArray.get(i).toString());
if (jsonObject.get("id").toString().equalsIgnoreCase("13")) {
System.out.println("Name: " + jsonObject.get("name"));
//do your thing...
}
}
Output:
Name: Another Something
I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests
I've been having some problems iterating through a JSON object in Java.
Specifically, I'd like to save each value for "name" to the string array "nameList". I've looked up how to do this, and I haven't found a way for this situation.
String[] nameList = new String[]{};
{
"data": {
"Narray": {
"0":
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
"1":
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
}
}
Ideally you'd want Narray to be an actual JSON array, enclosed in [], with each element being another object, containing the property you need, like this:
{
"Narray": [
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
]
}
Then you can use jackson to decode the JSON string into a POJO structure. Once you have the objects, you can iterate over the array and retrieve the property you need into a list.
I assume that you only want to save each value of name into a String[] (string array), so you don't need to deserialize the JSON string to POJO, just use basic API to achieve what you want as follows:
BTW, your JSON string is invalid, you miss a right bracket.
ObjectMapper mapper = new ObjectMapper();
JsonNode nArray = mapper.readTree(jsonStr).get("data").get("Narray");
String[] nameList = new String[nArray.size()];
for (int i = 0; i < nArray.size(); i++) {
nameList[i] = nArray.get(String.valueOf(i)).get("name").asText();
}
System.out.println(Arrays.toString(nameList));
Console output:
[studio, venue]
I need to get the values of the array "q1" which in array "questions", the arrays is json, and i need the values in java android.
{
"questions": [
{
"q1": [
"what my name?",
"a",
"b",
"c",
"Mac"
],
"q2": [
"what my age?",
"1",
"34",
"80",
"3"
]
}
]
}
Here I am answering your question to solve your problem but My friend you need to study first about json parsing.
Suggestion :
You can find example of it here :
http://primalpappachan.com/android/2010/06/05/parsing-json-in-android/
Answer :
JSONObject jresonseobj = response.getjObj();
JSONObject jobj;
JSONArray jsonArray = new JSONArray(jresonseobj.getString("questions"));
for (int i = 0; i < jsonArray.length(); i++)
{
jobj = jsonArray.getJSONObject(i);
// parse inner json here.
}
I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}