As the tital states above I am trying to replace the value for "name" to "abc" but that does not seem to overwrite it as it's the same value after replacing it using the Simple Json java code.
This is my java code:
String jsonString =
"{"
+ "\"data\":"
+ "["
+ "{"
+ "\"jazz\":\"black\","
+ "\"name\":\"white\","
+ "\"given\":\"red\","
+ "\"sam\":\"blue\","
+ "\"mail\":\"yellow\","
+ "\"member\":\"green\","
+ "\"department\":\"green\","
+ "\"title\":\"green\""
+ "}"
+ "]"
+ "}";
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(jsonString);
JSONObject newJSON = new JSONObject();
jsonObj.remove("name");
jsonObj.put("name", "abc");
As I said, the code above seems to not do anything for the "name" attribute that's already in the json structure. The output for the above looks like this:
{
"data": [
{
"given": "red",
"mail": "yellow",
"jazz": "black",
"name": "white",
"member": "green",
"department": "green",
"title": "green",
"sam": "blue"
}
],
"name": "abc"
}
What the output should look like:
{
"data": [
{
"given": "red",
"mail": "yellow",
"jazz": "black",
"name": "abc",
"member": "green",
"department": "green",
"title": "green",
"sam": "blue"
}
]
}
Any idea as to why its not changing it?
UPDATE 1
this worked for me:
JSONArray jsonArray = (JSONArray)jsonObj.get("data");
JSONObject jsonObject = ((JSONObject)(jsonArray).get(0));
jsonObject.put("name", "abc");
System.out.println(jsonObj.toJSONString());
You have the object inside you json object
You need to get the inner data object and modify it
jsonObj.get("data").put("name", "abc")
Time to time you can be faced with situations where would be perfect to replace some values in flexible way. So I'd like to show this additional approach using json-path dependency.
Specify path collection to replace real data, for example:
import static com.google.common.collect.Lists.newArrayList;
...
private static final List<String> PATHS_TO_REPLACE = newArrayList(
"$.email",
"$.colleagues.[*].email",
"$.other.required.pathmask"
);
And most important code part:
public String maskSensitiveData(String asJson) {
DocumentContext parsed = JsonPath.parse(asJson);
PATHS_TO_REPLACE.forEach(path -> parsed.set(path, "***starred***"));
return parsed.jsonString();
}
To avoid of com.jayway.jsonpath.PathNotFoundException if you sure they have to be suppressed, you can use special configuration:
private static final Configuration CONFIGURATION = Configuration
.builder()
.options(Option.SUPPRESS_EXCEPTIONS)
.build();
and parseddocument should be given in updated way:
DocumentContext parsed = JsonPath.using(CONFIGURATION).parse(asJson);
To play with code I'd recommend try prepared test for correspond service.
P.S.
If you want calculate stars for setting value (or hide only part of data) in dynamic way it also can be handled. To keep it simple for data arrays, please pay your attention on map method of the same object. Correspond example also added to the service:
public String flexibleMaskingSensitiveData(String asJson) {
DocumentContext parsed = JsonPath.using(CONFIGURATION).parse(asJson);
PATHS_TO_REPLACE.forEach(path -> parsed.map(path,
(currentValue, conf) -> starringCurrentValue(currentValue)));
return parsed.jsonString();
}
private Object starringCurrentValue(Object currentValue) {
return ofNullable(currentValue)
.filter(String.class::isInstance)
.map(String.class::cast)
.map(String::length)
.map(times -> StringUtils.repeat('*', times))
.orElse("");
}
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 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.
At the moment i'm trying to understand json and how it works.
But i have a problem with an array of objects.
all objects in the array have a key called "value" (i know it's weird, it's not my code) what also is an object.
And now to the problem: This object called "value" has always different key-values.
So i dont now how i can parse the json code to java object code, when it differ, every time.
Here some examples:
First object of the array:
"value":
{
"local":
[
"English", "Deutsch", Espanol"
],
"english":
[
"English", "Deutsch", Espanol"
],
},
Second object(now a string, not object) of the array:
"value" : "",
Third object of the array:
"value" : {},
...
Maybe I'm doing the parsing wrong.
First I have created the beans classes in java for the json code and then I'm using the automatic parser of google. (gson)
It works when only one of the examples above is inside the json code. (it should not differ, like changing from string to object...)
Gson gson = new Gson();
Output output = gson.fromJson(json, Output.class);
Output is the main class for the json stuff.
I have found out that maybe while parsing I could check a value called "id" first, and from that I could create another beans class with the right variables ...
Thats the code i need to parse to java objects and how do you do that??
The problem is the key called "value", because its always different.
With my method of using the google parser "gson" it wont work, because i'm getting exception that its an string but i was waiting for an object...
{
"status":"success",
"data":{
"panel":{
"title":{
"label":{ "local":"Tote Selection", "english":"Tote Selection" },
"image":"public/img/pick.jpg", "type":"default"
},
"isFirst":false, // currently not used
"isLast":false, // currently not used
"ownCount":0, // currently not used
"panelsCount":0, // currently not used
"elements":[
{
"type":"text",
"id":"1", "value":{ "local":"Scan next order tote",
"english":"Scan next order tote" },
"label":{ "local":"", "english":"" }, "color":"000000",
"fontsize":18, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "bgcolor":"", "isFocus":false
},
{
"type":"text",
"id":"4", "value":{ "local":"Scan tote: ", "english":"Scan tote: " },
"label":{ "local":"", "english":"" }, "color":"000000", "fontsize":20,
"fontstyle":"strong", "alignment":"left", "rows":"undefined",
"bgcolor":"", "isFocus":false
},
{
"type":"input",
"id":"6", "value":"", "label":{ "local":"", "english":"" },
"color":"000000", "fontsize":24, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "isFocus":true
},
{
"type":"button",
"id":"1", "value":{ "local":"", "english":"" },
"label":{ "local":"Menu", "english":"Menu" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"left",
"rows":"undefined", "isFocus":false
},
{
"type":"button",
"id":"4", "value":{ "local":"", "english":"" },
"label":{ "local":"Enter", "english":"Enter" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"right",18
"rows":"undefined", "isFocus":false
}
]
},
"authToken":"0fdd440a-619f-4936-ab74-d189accb5bd9",
"routing":{
"controller":"panel",
"action":"process",
"workflowId":"singlepicking",
"taskId":"orderSelection"
}
}
}
Thank you for your help!
it looks a little bit different but your answer helped me! Thx
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(br).getAsJsonObject();
//now getting all the json values
String status = obj.get("status").getAsString();
JsonObject data = obj.getAsJsonObject("data");
String authToken = data.get("authToken").getAsString();
JsonObject routing = data.getAsJsonObject("routing");
String controller = routing.get("controller").getAsString();
String action = routing.get("action").getAsString();
String workflowId = routing.get("taskId").getAsString();
If I understood ur question properly u can retrieve the values of the JSONArray as below
for (int i = 0; i < JArray.length(); i++) {
print(JArray.getJSONObject(i).tostring())
}
So if i am right u are getting the JSON from a String First?? so please try below first store the String in JSONObject as JSONObject obj = new JSONObject(str);//str is the string that u are getting
to get the valueenglish that are in data-panel-tittle-label is
String englishinLable=obj .getJSONObject("data").getJSONObject("panel").getJSONObject("title").getJSONObject("label").optString("english")
I know its an array, but I am completely new to JSON and need help comprehending how this is structured, here is my attempt at extracting data:
String JSonString = readURL("//my URL is here");
JSONArray s = JSONArray.fromObject(JSonString);
JSONObject Data =(JSONObject)(s.getJSONObject(0));
System.out.println(Data.get("name"));
My JSON data that I have goes like this :
{
"sports": [
{
"name": "basketball",
"id": 40,
"uid": "s:40",
"leagues": [
{
"name": "National Basketball Assoc.",
"abbreviation": "nba",
"id": 46,
"uid": "s:40~l:46",
"groupId": 7,
"shortName": "NBA",
"athletes": []
}
]
}
],
"resultsOffset": 10,
"resultsLimit": 10,
"resultsCount": 1,
"timestamp": "2013-11-18T03:15:43Z",
"status": "success"
}
I dont really have a strong grasp of this stuff so all the help is appreciated.
Here is the idea :
JSONObject root = new JSONObject(yourJsonString);
JSONArray sportsArray = root.getJSONArray("sports");
// now get the first element:
JSONObject firstSport = sportsArray.getJSONObject(0);
// and details of the first element
String name = firstSport.getString("name"); // basketball
int id = firstSport.getInt("id"); // 40
JSONArray leaguesArray = firstSport.getJSONArray("leagues");
// and so on, you can process leaguesArray similarly
It should work (feel free to complain about compile errors if there are any)
Your JSON data is an object (it starts with a curly brace). In the next inner layer, there is a single array (at key "sports"):
String jsonString = readURL("//my URL is here");
JSONObject result = JSONObject(jsonString);
JSONArray sports = result.getJSONArray("sports");
JSONObject sport = sport.getJSONObject(0);
System.out.println(sport.getString("name"));
I might have used another JSON library than you.
JSON means JavaScript Object Notation.
Objects in javascripts are just containers and can be represented by key-value pairs. Please find below notations to understand about json.
Represent objects in json: E.g. Student
{"name" : "Robin", "rollnumber" : "1"}
Represent array in json : E.g. Array of students
[{"name" : "Robin", "rollnumber" : "1"}, {"name" : "Mark", "rollnumber" : "2"}]
You can understand more on JSON from diagrams on this link http://www.json.org/fatfree.html
There are various ways available to to convert JSON to javaobject and javaobject to JSON : One of them is http://wiki.fasterxml.com/JacksonInFiveMinutes
Adding detailed code here along with the imports .
If this helps.
import org.json.JSONException;
import org.json.JSONObject;
public class extractingJSON {
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
String jsonStr = "{\"name\":\"SK\",\"arr\":{\"a\":\"1\",\"b\":\"2\"},\"arrArray\":[{\"a\":\"1\",\"b\":\"2\"}]}";
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
System.out.println(name);
String first = jsonObj.getJSONObject("arr").getString("a");
System.out.println(first);
first = jsonObj.getJSONArray("arrArray").getJSONObject(0).getString("a");
System.out.println(first);
}
}
In java, I am trying to parse values from this json..
[
{
"2012-01-02": {
"age": 3,
"dob": "2010-01-03",
"name": "jack"
},
"2012-01-03": {
"age": 3,
"dob": "2010-01-04",
"name": "jill"
},
"2012-01-04": {
"age": 3,
"dob": "2010-01-05",
"name": "john"
},
"2012-01-05": {
"age": 3,
"dob": "2010-01-06",
"name": "miran"
}
}
]
Using JSONObject, I was trying to get the value of just "age" and then add them up to do some data manipulation.
I created a JSONObject
Created an iterator and then stored them to a map
This gets me the inner element like:
{
"age": 3,
"dob": "2010-01-06",
"name": "miran"
}
After this, not sure how to extract just age from each element. Do i create another jsonobject and pass this new string, extract age out of it or is there a better way to do this? (I am sure there is one)
UPDATE:
This is what I currently have that gives me {"age":3,"dob":"2012-01-06","name":"miran"}
JSONObject jsonobj = new JSONObject();
try {
jsonobj = new JSONObject(pastweekVol);
Iterator iter = jsonobj.keys();
Map<String, String> map = new HashMap<String, String>();
while(iter.hasNext()){
String jsonkey = (String)iter.next();
String value = jsonobj.getString(jsonkey);
logger.debug("first pass value is: {}", value);
} catch (JSONException je) {
logger.debug("exception is: {}",je);
}
I was thinking that since I am getting {"age":3,"dob":"2012-01-06","name":"miran"}, I would create another json object and pass in this string, which will give me value of "age". The problem here is that I get repetitive values. Of course, something very basic is missing here but I can't seem to figure that out.
If you have the inner element as a JSONObject instance - say person - then you can directly access the age:
int age = person.getInt("age");
and do something with it:
sum += age;
You might consider a library like Google's GSON (http://code.google.com/p/google-gson/) if you want to be able to easily parse arbitrarily complex JSON strnigs into generic objects.
Using org.json is probably not your best bet -- this API has many flaws. Using Jackson, you can easily extract age from each member value:
ObjectMapper mapper = new ObjectMapper();
JsonNode fullDocument = mapper.readTree(xxx); // xxx can be many things
// Not an object? Bail out
if (!fullDocument.isObject())
throw new IllegalArgumentException("not an object");
// This will iterate through object values
for (JsonNode value: fullDocument)
// do something with value.get("age")
// in particular, you can test for .isIntegralNumber()