I have a URL request like this:
http://localhost:8080:_dc=1367504213107&filter[0][field]=site&filter[0][data][type]=string&filter[0][data][value]=test&filter[1][field]=address&filter[1][data][type]=string&filter[1][data][value]=Columbus
This is the URL request that I get from browser.
From this URL, I need to get the filter related data as a JSON object.
Basically I have filter parameters like these in the requested URL:
filter[0][field]=site
filter[0][data][type]=string
filter[0][data][value]=test
filter[1][field]=address
filter[1][data][type]=string
filter[1][data][value]=Columbus
I am using the Spring MVC framework.
Those URL parameters aren't in JSON format. I'm not sure what your question / problem is here... can't you just read in each of those parameters from the URL and then parse the data out of the strings as you need? You could take it as a single parameter and tokenize based on a custom character, or you could just loop through all the parameters and parse each one and add them to an array.
Are you saying that you need to return the data in JSON format? Get your data using the parsed parameters as I described above, then when you have the data merely serialize that object and pass it back over the wire as the body of the response. You'll want to use a JSON serialization library like Jackson which will write the object to a string in JSON for you.
This is what that data would probably look like if it were written in JSON:
{
"filter":
[
{
"field": "site",
"data":
{
"type": "string",
"value": "test"
}
},
{
"field": "address",
"data":
{
"type": "string",
"value": "Columbus"
}
}
]
}
Java code that translates from the above JSON to your-format:
JSONObject root = new JSONObject(json);
JSONArray filters = root.getJSONArray("filter");
for (int i = 0; i < filters.length(); i++)
{
JSONObject filter = filters.getJSONObject(i);
String field = filter.getString("field");
JSONObject data = filter.getJSONObject("data");
String dataType = data.getString("type");
String dataValue = data.getString("value");
System.out.println("filter[" + i + "][field]=" + field);
System.out.println("filter[" + i + "][data][type]=" + dataType);
System.out.println("filter[" + i + "][data][value]=" + dataValue);
}
Your data format does not appear to be standard, so you will have to parse it yourself.
Related
I have a string like below
{
"id": "abc",
"title": "123.png",
"description": "fruits",
"information": [
{
"type": "apple",
"url": "https://apple.com"
},
{
"type": "orange",
"url": "https://orange.com"
}
],
"versions": 0
}
I want to get the value of url where type: orange. The list in information may not always be in same order as appearing in the data above. I know I could do it easily in python with json.loads and json.dump.
I am trying to do it java using JsonNode and objectMapper.readTree.at("/information") but I am unable to get past this point in a clever neat way to get the list and fetch the url where type = orange.
This is pretty straightforward
Use a JSON library and parse the response using the library. Then get only the values and attributes that you need...
Example relevant to your case:
// Get your Json and transform it into a JSONObject
JSONObject mainObject = new JSONObject(yourJsonString); // Here is your JSON...
// Get your "information" array
JSONArray infoArray = mainObject.getJSONArray("information"); // Here you have the array
// Now you can go through each item of the array till you find the one you need
for(int i = 0 ; i < infoArray.length(); i++)
{
JSONObject item = participantsArray.getJSONObject(i);
final String type = item.getString("type");
final String url = item.getString("url");
if(type.equals("orange"))
{
// DO WHATEVER YOU NEED
}
}
I am trying to do JSON parsing. The JSON data is shown below, I am trying to get the "categories". I was able to JSON parse everything else, but I am not sure what does this "categories" belong to, is it a JSONObject, JSONArray, or something else? I am a newbie and self-taught, usually I am familiar that JSONArray has form of "JSONArray": {["content"]}, and the "content" is JSONObject. But in this case, "categories":["content"]. I am trying to parse this "categories", and turn it to string. Thank you for your help.
{
"results": [
{
"type": "Restaurant",
"id": "jfhuiewjkfkdljiahueijkfnlsdiejkl1484391hjk8421k",
"score": 99.9844207764,
"dist": 15.581982823437135,
"info": "search:ta:840369014527642-US",
"poi": {
"name": "RoofTop Bar",
"categorySet": [
{
"id": 184729472943
}
],
"categories": [
"pub food",
"restaurant"
]}
}]
}
This is what I have tried:
groups = new JSONArray();
groups = response.getJSONArray("results");
if (groups.length() > 0) {
JSONObject resultObject = groups.getJSONObject(0);
if (resultObject.has("poi")) {
if (resultObject.getJSONObject("poi").has("name")) {
nameResult = resultObject.getJSONObject("poi").getString("name");
} else {
nameResult = "Information is not available.";
}
if (resultObject.getJSONObject("poi").has("categories")) {
JSONObject categoriesResult;
categoriesResult = resultObject.getJSONObject("categories").toString();
}
results is an array of objects
The first object contains a property called poi
poi contains a property called categories
So using the top to bottom approach, we can arrive at
const categoriesArray = results[0].poi.categories; // gives categories as an array of strings
const categoriesString = categoriesArray.join(",") // gives categories as string, with comma separated values
I am not sure if it is the actual raw data but the poi object where the categories are contained is malformed. It is missing a closing bracket which could be causing parsing issues.
That apart, the field categories from the poi object is a list of strings I am not sure how you want to format it to a string but you could loop through them and do want you want with them.
In order to obtain them you can access them from your object with results[0].poi.categories or loop through the results before accessing the categories with result.poi.categories where result is the variable containing the currently looped result.
EDIT:
From your code sample, assuming response is a JSONObject you can do the following.
Then to obtain categories in a string without the array format, you can loop through the categories and concatenate them to a string.
String categories = resultObject.get("categories").join(", ");
I have same query. My JSON is as below.
String json="{ "credentials": { "password": "Password"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
key = password and value is "Password"123" it contains " (double quote).. I am not able to create a java object from this json as it is invalidated.
Gson gson = new Gson();
gson.fromJson(json, PasswordResetDetails.java);
Above code snippet is not Working.
If you are doing this for learning / testing purpose all you need to do is escaping the double quote using :
String json="{ "credentials": { "password": "Password\"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
If this is a real scenario then I would like to suggest to change the source in order to make sure it provides valid JSON.
There are countless possibilities to check if your JSON is valid (JSON linting), here's one.
I am building a tool using java, that accesses an API.
I'm trying to let the user decide, which parameters to use (via checkboxes for instance).
So the user would decide to take one of let's say 5 parameters:
p1
p2
p3
p4
p5
and then I would make a call to the API using those parameters and receive a Json String as a response.
So that Json String can be either
{"data":[{"p1":"value1", "p2":"value2", "p3":"value3", "p4":"value4", "p5":"value5"}]}
{"data":[{"p1":"value1", "p2":"value2", "p3":"value3", "p4":"value4"}]}
{"data":[{"p1":"value1", "p2":"value2", "p3":"value3"}]}
{"data":[{"p1":"value1", "p2":"value2"}]}
or
{"data":[{"p1":"value1"}]}
I'm trying to print everything inside "data" to the console. This is the code I got so far:
JsonParser parser = new JsonParser();
JsonObject json = (JsonObject)
parser.parse(adsInsights.toString());
System.out.println(json.get("p1").getAsString() + "\t"
+ json.get("p2").getAsString() + "\t"
+ json.get("p3").getAsString() + "\t"
+ json.get("p4").getAsString() + "\t" +
json.get("p5").getAsString()
);
My problem is: how do I determine which ones to print, without doing a ton of if/elses?
All I need is every variable within "data". is there a method to do this?
EDIT:
First of all, thanks for all the answers.
For future reference I guess, this is what I did:
//getting the keys, which the user has selected. Detailed implementation irrelevant for this matter
String selectedKeys[] = getSelectedKeys();
JsonParser parser = new JsonParser();
JsonObject json = (JsonObject)
parser.parse(adsInsights.toString());
for(int i = 0; i < selectedKeys.length; i++) {
if(json.has(selectedKeys[i])) {
System.out.print(json.get(selectedKeys[i]).getAsString() + "\t");
}
}
System.out.println();
You can iterate over the Json keys no matter which keys are in it and print their values.
JsonParser parser = new JsonParser();
JsonObject json = (JsonObject)
parser.parse(adsInsights.toString());
for (key: json.keys) {
System.out.print(json.get(key).getAsString());
}
// to check if key exists or not. if not, return empty string.
private String getValues(JSONObject jsonObj, String arg) {
return jsonObj.get(arg) != null?(String) jsonObj.get(arg):"";
}
//call getValues function for every key. fetch all keys from keySet Function.
JSONObject check=(JSONObject) obj;
JSONObject data=(JSONObject) check.get("data");
Set<String> keys=data.keySet();
for(String k:keys){
System.out.println(getValues(data,k));
}
Are you building the API as well?
I think a better data structure to return from the API would be to use an array for "data", e.g.
{
"data":[
{ "id": "p1", "value": "value1" },
{ "id": "p2", "value": "value2" },
{ "id": "p3", "value": "value3" },
{ "id": "p4", "value": "value4" },
{ "id": "p5", "value": "value5" }
]
}
That way, the receiving code doesn't have to care about which items are in data, or how many. Instead it can just loop through the array and print whatever happens to be there.
I'm new to JSON and have below file. I have to save the array "steps" in java and need to loop the objects "duration" , "status" and "Keyword".
"steps": [
{
"result": {
"duration": 7128811788,
"status": "passed"
},
"line": 5,
"name": "The Browser is Launched and Smart Business URL is loaded",
"match": {
"location": "Common_Login.the_Browser_is_Launched_and_Smart_Business_URL_is_loaded()"
},
"keyword": "Given "
},]
I tried below but didn't worked.
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("./target/JSON/Output.json"));
JSONArray jsonArray = (JSONArray) obj;
System.out.println(jsonArray);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) jsonArray.get(i);
name = (String) jsonObjectRow.get("duration");
id = (String) jsonObjectRow.get("status");
uri = (String) jsonObjectRow.get("name");
status = (String) jsonObjectRow.get("location");
}
Refer here.
There are so many libraries build in for doing this task. But look at the question above.
If you want to use the built-in class from Java you can have a look here:
https://stackoverflow.com/a/17399110/3977134
You are missing the part from the parseJson function in the referenced answer.
For simplicity I'd suggest to you to use org.json which is just one of many good libraries to use for JSON parsing in Java. If you are interested see here:
Parse JSON with org.json
Parsing JSON in Java Using org.json