I have this JSON:
{
"-1":{
"name":"Ad hoc",
"modifiedBy":"",
}
},
"9":{
"name":"my name",
"modifiedBy":"me",
}
}
}
The tags "-1" and "9" are IDs that I don't know.
I need get the tag "9" using the "name" "my name" with a JSON path.
How can I do that? I use Java.
I'm assuming the JSON in your question is in Java's JSONObject form. Let's call this object myjson. Let's also say you are trying to get the ID of the sub-object that has an internal "name" value of "Ad hoc":
String nameKey = "Ad hoc";
String theID = "";
Set keys = myjson.keySet();
Iterator iter = keys.iterator();
while(iter.hasNext()) {
String key = (String)iter.next();
String name = (String)jsonObject.getJSONObject(key).get("name");
if (name.equals(nameKey)) {
theID = key;
}
}
The variable theID should now contain the ID you want. If no match is found, theID will be an empty string.
Related
I've got the URI like this:
http://localhost:8080/profile/55cbd?id=123&type=product&productCategories.id=ICTLicense&productCategories.name.firstName=Jack&productCategories.name.lastName=Sparrow&groups=a&groups=b
I need a JSON object like this:
{
"id": "123",
"type": "product",
"productCategories": {
"id": "ICTlicense",
"name": {
"firstName": "Jack",
"lastName": "Sparrow"
}
},
"groups":["a", "b"]
}
Query parameters nesting can be dynamic, like for example abc.def.ghi.jkl.mno=value1&abc.xyz=value2 will result in
{
"abc": {
"def": {
"ghi": {
"jkl": {
"mno": "value1"
}
}
},
"xyz": "value2"
}
}
I have tried this but it can not handle the nesting.
final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(request.getQuery());
How to do this in Java?
With the way that your URI string is structured it wouldn't be possible to nest it the way you'd like, here's why.
id=123 This is simple enough since id would just be an int
productCategories.id=ICTLicense This would also be simple enough since we can assume that productCategories is an object and id is a key inside of the object
However, it gets more complex when you start using arrays, for instance:
&groups=a&groups=b
How do you know that groups is an array, and not simply a key called groups with a value of a or b
Also, you store all your data to Map<String, String>,
This wouldn't support arrays as it stores objects to key-value, so you wouldn't be able to have multiple keys of groups with different values.
I'd also suggest you use a library like Gson and parse your data to a JsonObject
https://github.com/google/gson
If you were to use Gson, you could do something similar to this:
public JsonObject convertToJson(String urlString) {
//Create a JsonObject to store all our data to
JsonObject json = new JsonObject();
//Split the data part of the url by the props
String[] props = urlString.split("&");
//Loop through every prop in the url
for (String prop : props) {
//Create a list of all the props and nested props
String[] nestedProps = prop.split("=")[0].split("\\.");
//Get the actual key for our prop
String key = nestedProps[nestedProps.length - 1];
//Get the value
String value = prop.split("=")[1];
//Loop through our props array
for (String nestedProp : nestedProps) {
//If the property already exists, then skip
if (json.has(nestedProp)) continue;
//If the prop is the key, add it to the json object
if(nestedProp.equalsIgnoreCase(key)) {
json.addProperty(nestedProp, value);
continue;
}
//If the above checks fail, then create an object in the json
json.add(nestedProp, new JsonObject());
}
}
return json;
}
I am trying to parse a map and update the value in it...
Here is the content of the .txt file that I have made the hashmap
The first line is the key and the JSON string is the value.
Not_enough_parameters
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:8", "version": "0.97", "coreName": "Patient_Responsibility"}
Here is my parsing code:
parse = params.split("\\|");
String key;
String value;
String value2;
String key2;
String value3;
Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();
if(parse.length!=18) {
key = "Not_enough_parameters";
value = predictionFeatureMap.get(key);
Map<?,?> resultJsonObj = new Gson().fromJson(value, Map.class);
key2 = "errorMessage";
value2 = (String) resultJsonObj.get(key2);
value3 = value2.substring(0,61) +parse.length+value2.substring(62);
}
I am sending a payload string named params that is separated by "|" separators. They input must have 18 parameters(18 values in-between the "|" separators). I parse the input and if it does not have enough parameters I get they key containing the string "Not_enough_paramters" and then get its value which is the JSON string.
I then take that JSON string and using Gson create a map out of it.
I did that because I want value to return
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:(params.length)", "version": "0.97", "coreName": "Patient_Responsibility"}
So I want "actual:" to be updated. I get the value from the JSON map for "errorMessage" and using substring I get the index and change the value to update the actual amount of parameters the user put in.
I am not sure how to reinsert the new JSON into the entire JSON string in the JSON map and then into the original map.
So I implemented a solution although I am not sure it is the cleanest and most straight forward.
I still got the substring from the value from the "errorMessage" key in the JSON Map.
I then replaced the value of that key with the new edited JSON.
Then I took the Json Map and converted it into a string.
I then added the new JSON string to the value of the original hashmap
String[] parse;
#PostMapping(value = "/")
public String payloader(#RequestBody String params ) throws IOException{
LOGGER.debug("code is hitting");
String key,key2;
String value,value2,value3;
Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();
if(parse.length!=18) {
key = "Not_enough_parameters";
value = predictionFeatureMap.get(key);
Map<String,Object> resultJsonObj = new Gson().fromJson(value, Map.class);
key2 = "errorMessage";
value2 = (String) resultJsonObj.get(key2);
value3 = value2.substring(0,61) +parse.length+value2.substring(62);
resultJsonObj.replace(key2, value3);
String updatedResponse = new Gson().toJson(resultJsonObj,Map.class);
value = updatedResponse;
}
else {
key = params;
value = predictionFeatureMap.get(key);
}
return value;
JSON values that I get from server:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
Getting the result as 'response' after connection and I am able to show my JSON string results on the screen.
JSONObject json = new JSONObject(response);
String status = json.getString("Status");
String message = json.getString("Message");
String result = json.getString("Result");
responseView.setText("Status" + status+ "Message" + message" + Result" + result);
I am okay the results of "Status" and "Message" but not with "Result" because want to separate "Result" objects as and able use each of them as objects.
For example:
When I type OB in my app, I will get the result S.C. Blue Air
Instead of :
String result = json.getString("Result");
use
if(json.get("Result") instanceof JSONObject){
JSONObject object = (JSONObject) json.get("Result");
//do what you want with JSONObject
String ob = object.get("0B");
}
If you want to store it some way you can put it to Map or create object if always it is same data
You can use some libraries such as Gson (Google) or Moshi (Square)
Those libraries allows you to declare your model as a plain java class (commonly called POJOS) annotated in some way that this libraries bind your properties in the JSON to your java properties.
In your case:
JSON:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
MODEL:
public class MyCallResponse {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("0B")
String b;
#SerializedName("0Y")
String y;
#SerializedName("0X")
String x;
}
In this case, with Gson you can do:
MyCallResponse response = new Gson().fromJson(json, MyCallResponse.class);
Log.i("Response b", response.result.b);
Look at the documentation for more information about both libraries.
try this :
JSONObject json = new JSONObject(response);
JSONObject resultObj = json.getJSONObject("Result");
String OB = resultObj.getString("OB");
Try this
String base = ""; //Your json string;
JSONObject json = new JSONObject(base);
JSONOBject resultJson = json.getJSONObject("Result");
// Get all json keys "OB", "OY", "1X" etc in Result, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = resultJson.entrySet();
Iterator iterator = entrySet.iterator();
for (int j = 0; j < entrySet.size(); j++) {
String key = null; //key = "OB", "OY", "1X" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "OB", "OY", "1X" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = resultJson.getString(key);
//for key = "0B", value = "S.C. Blue Air"
//for key = "0Y", value = "FlyYeti"
//for key = "1X", value = "Branson Air"
}
}
It works with any array with dynamic json key.
Don't forget to accept the answer & upvote if it works.
I have a json object how can I get all the keys and later without hard coding the keys how can I get the key values.
{
"A":"M1",
"Data":[
{
"B":[
{
"B1":"111",
"B2":"Warning "
},
{
"B1":"222",
"B2":"Warning "
}
],
"C":[
{
"c1":"IL2",
"c2":"[0.750183,0.00933380975964486]"
},
{
"c1":"IL1b",
"c2":"[0.750183,-1.5216938335421]"
}
]
}
]
}
Try this out...
This might work for you....
You have to use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
Roughly the code will look like:
// searchResult refers to the current element in the array "search_result"
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
// do something here with the value...
}
I am developing simple web application to learn jsp, mongodb, html. I have created an simple registration form in jsp which takes Name, Address and MobileNo information from user and insert it into mongodb, Now I want to retrieve this stored data and put value of every field in individual string variable.
Ex:
Name: varun; Address: Nagpur; MobileNo: 1234567890
Above data is stored in mongodb as:
{
"_id" : ObjectId("5259bacea6f8b1c4cd3431d3"),
"Name" : "varun",
"Address" : "nagpur",
"MobileNumber" : "1234567890"
}
Retrieved in jsp as follows:
MongoClient mongoC = new MongoClient(new ServerAddress("Localhost",27017));
DB database = mongoC.getDB("dbfrnzout");
DBCollection collec1 = database.getCollection("coll");
DBObject dock= collec1.findOne();
out.println(dock);
This code print one record as json document and I want to store value associated with every
field in individual string variable, something like this:
String s1 = varun ie. value of field Name
Need some guidance.
DBObject implements the Map<String, Object> interface so you should be able to do something like:
String name = (String) dock.get( "Name" );
String address = (String) dock.get( "Address" );
String mobileNumber = (String) dock.get( "MobileNumber" );
Be careful with the casts and make sure you are certain of the type and existence of each field. For numeric values I strongly recommend casting to a Number instead of Integer since MongoDB will re-cast values to a Long or Double at the weirdest times.
HTH, Rob.
Edit: If you are iterating over the results of a query you will have to inspect each document as it is returned from the iterator
DBCollection collec1 = database.getCollection("coll");
for( DBObject dock : collec1.find() ) {
String name = (String) dock.get( "Name" );
String address = (String) dock.get( "Address" );
String mobileNumber = (String) dock.get( "MobileNumber" );
// Do Something...
}
Do something like this to get an object from a cursor
while (cursor.hasNext())
dbObject o = cursor.next()