I've got a JSON response that looks like this:
USER:[{
"id":"145454",
"name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true,
"caregiverName":"Jones"
}]
I'm trying to create a java method so I can access the key value pairs of the nested JSONArray. For example I don't want the entire JSON array I just want to retrieve the doctor name from the patientInfo JSON array. Any ideas how I would do this in Java I'm completely stuck here.
This is sudo code but I imagine it would be something like:
String doctorInfo() {
JSONObject obj = new JSONObject(user)
JSONArray arr = obj.getJSONArray("patientInfo")
String doctor = arr.getValue("doctor")
}
And I'd like to be able to access it on the front end by doing
doctorInfo().doctor
Code samples are greatly appreciated.
The code will be like this:
String doctorInfo(String jsonString) {
JSONObject obj = new JSONObject(jsonString)
JSONArray arr = obj.getJSONArray("patientInfo")
JSONObject patientJSONObject = arr.getJSONObject(0);
String doctor = patientJSONObject.getString("doctor");
return doctor;
}
The above code sample assumes you are passing the below string as the parameter.
{ "id":"145454", "name":"JJones",
"patientInfo":"[{"id":"12334", "doctor":"Smith"}]",
"insurance":true, "caregiverName":"Jones" }
Related
I have a java spring boot project that makes an REST API call and one element of the returned json is as follows:
"args": "[[\"element_1\"],[\"element_2\"],[\"{\\\"payload\\\":\\\"{\\\"Header\\\": \\\"Header_title\\\", \\\"Content\\\": \\\"Content of the payload\\\"}\\\"}\"]]"
My objective is to get the JsonObject "payload". I can get the string using
JsonObject argString = (JsonObject) jsonParser.parse(originalJsonObject.get("args").toString());
(using the package com.google.gson.JsonObject) but I can't get the two-dimensional array out of the string.
The part of data that you've included actually is a key args with a string value [[\"element_1\"],[\"element_2\"],[\"{\\\"payload\\\":\\\"{\\\"Header\\\": \\\"Header_title\\\", \\\"Content\\\": \\\"Content of the payload\\\"}\\\"}\"]]. So it is correct that you cannot get these contents decoded through a method on the existing Json, but you can take the string and parse it to a json array as follows:
JsonElement jsonElem = new JsonParser().parse(argString);
JsonArray jsonArray = jsonElem.getAsJsonArray();
for(int i = 0; i < jsonArray.size(); i++) {
System.out.println(jsonArray.get(i));
}
I have a String like this:
{"api_authentication":{"api_response":{"token":"XXXXXXXXXXXXXXXXXXXXXXXXX","firstname":"John","disabled":false,"attempts":0,"id":123,"lastname":"Malkovitch","expire":false,"status":0}}}
I can turn this string into an object:
JSONObject jobj = new JSONObject(response);
But I don't find how to get the token value, I tried creating JSONArrays but i get a not found exception.
You can do it like this ;
final JSONObject api_authentication = jobj.getJSONObject("api_authentication");
final JSONObject api_response = api_authentication.getJSONObject("api_response");
System.out.println(api_response.getString("token"));
if JSON any value in curlybrackets { ... } , this is jsonObject . If values are in [ ... ], this is JsonArray. Also you can get which one is object or array, and get it relevant fields from this. So all of json elements are with curly bracket in your problem. Get it as JsonObject.
this might work by the look of what you have posted. The posted code snippet shows that it is a single JSON object and not a JSONArray.
Hence try the following:
JSONObject jobj = new JSONObject(response);
String newtoken = jobj.getJSONObject("api_authentication").getJSONObject("api_response").getString("token"); //declare the variable `newtoken` somhwere before of a desired type
You could try something like:
Object tokenValue = jobj.getJSONObject("api_authentication").getJSONObject("api_response").get("token");
After that you can cast the object to the desired type or use something like getString(.) straightaway.
[{"period":"","billing_mode":"checked","price":"1500","bundleid":0,"name":"hello stack","deviceid":"923is3j4","date":"2016-06-23","userid":0,"type":"mobile","strutid":999}]
I have this JSON Array inside which JSON Objects like above were there.
I want JSON Objects which has
"period":""
to get deleted.Is it possible?Please help me thanks.
P.S:This is for Java not Javascript.
See you can do using this way
This is for PHP guy :)
$json='{"period":"","billing_mode":"checked","price":"1500","packageid":0,"name":"hello stack","subscriberid":"9283is3j4","date":"2016-06-23","serviceid":0,"type":"event","programid":999}';
$arr = json_decode($json, true);
unset($arr['period']);
echo json_encode($arr);
If you want in java then using java-json.jar you can achieve it as following:
public static void main(String[] args) throws JSONException {
String s="{\"period\":\"\",\"billing_mode\":\"checked\",\"price\":\"1500\",\"packageid\":0,\"name\":\"hello stack\",\"subscriberid\":\"9283is3j4\",\"date\":\"2016-06-23\",\"serviceid\":0,\"type\":\"event\",\"programid\":999}";
JSONObject jsonObj = new JSONObject(s);
JSONArray nameArray = jsonObj.names();
List<String> keyList = new ArrayList<String>();
for (int i = 0; i < nameArray.length(); i++) {
keyList.add(nameArray.get(i).toString());
}
for (String key : keyList) {
if (jsonObj.get(key).equals(""))
{
jsonObj.remove(key);
}
}
System.out.println(jsonObj.toString());
}
If we remove a JSON Key While Iterating JSONArray then it will give following exception:
Exception in thread "main" java.util.ConcurrentModificationException
So i have achieved by copying the JSON array into a Java collection and used the JSONObject.names() method to obtain a JSONArray of keys.
I am trying to get the name of my json key from my jsonarray but not able to take in java.
[{"ParamName":"param1","DefaultValue":"","Hidden":"Hidden","LinkedParameter":"city"}]
I just want to take name of key like i only want to take "ParamName" and need to check
if (ParamName == "ParamName") {
Then do this.
}
You can convert this to JSON object.
JSONArray json = (JSONArray)new JSONParser().parse("[{\"ParamName\":\"param1\",
\"DefaultValue\":\"\",\"Hidden\":\"Hidden\",\"LinkedParameter\":\"city\"}]");
JSONObject obj= (JSONObject) json.get(0);
if("ParamName".equals(obj.get("ParamName"))){
}
In the client side, I have constructed a JSOnARRAY like this:
{"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
On the server side (java), I can retireve the values using :
jfilter = JSONValue.parse(jsonFilterStr); //jsonFilterStr={"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
JSONArray jFilterEntries = (JSONArray) jfilter.get("filterEntries");
for (int i=0;i<jFilterEntries.size();i++){
JSONObject jFilterEntry = (JSONObject) jFilterEntries.get(i);
String dataName = (String) jFilterEntry.get("dataName");
String filterValue = (String) jFilterEntry.get("filterValue");
}
But the existing app is using flex.json.deserializer and I am unable to achieve the same using flex.json.deserializer. How should I proceed?
I wish to do something like this:
JSONDeserializer jsonDeserializer = new JSONDeserializer();
jsonDeserializer.use(null, List.class);
List<Map<String,String>> lMap= (List<Map<String,String>>)jsonDeserializer.deserialize(params);
Remember the top object that wraps the array. You have to handle that as well. You have to tell it to expect a Map inside the List. To do that you have to specify the type contained in the list by using the path expression "values".
Map<String,List<Map<String,String>>> result = new JSONDeserializer<Map<String,List<Map<String,String>>>>()
.use("values",List.class)
.use("values.values", Map.class)
.deserialize( json);
List<Map<String,String>> filterEntries = result.get("filterEntries");
Updated: Add the new keyword, and made the generic types on the right match the left.