I wrote a small code to validate that my request fails when some part of it is removed.I want to remove the product element and its value.
Here's the request
{
"product": "tv",
"price": "45",
"payment": {
"credit_card": {
"number": "1234567891234567",
"type": "Visa",
"expire_month": 10,
"expire_year": 2019,
"cvv2": 999,
"first_name": "John",
"last_name": "Smith"
}
}
}
This is the code snippet -
JSONParser parser = new JSONParser();
String requestFile = System.getProperty("user.dir") + "/src/test/resources/request/request.json";
logger.info("Loading request file: " + requestFile);
Object obj = parser.parse(new FileReader(requestFile));
JSONObject jsonObject = (JSONObject) obj;
//fails on the below line saying Java.lang.String cannot be cast to org.json.simple.JSONObject
// What's the alternative?
logger.info("printing json object "+jsonObject.get("product"));
jsonObject = (JSONObject) jsonObject.remove("product");
System.out.println("Now the request is "+jsonObject);
I was able to resolve this problem.
Here's the code snippet after making changes in it.
JSONParser parser = new JSONParser();
String requestFile = System.getProperty("user.dir") + "/src/test/resources/request/original_request.json";
logger.info("Loading request file: " + requestFile);
Object obj = parser.parse(new FileReader(requestFile));
Object jsonObject = (JSONObject) obj;
//remove product_name
((HashMap) jsonObject).remove("product");
logger.info("New request "+jsonObject);
Related
I need to create JSON data like below,
{
"min": {
"week": "1",
"year": "2014"
},
"max": {
"week": "14",
"year": "2017"
}
}
But JSONObject accepts only "id","value" format.
So how can I create JSON data using JSONObject like mentioned above.
That is very easy, here is an example:
JSONObject min = new JSONObject();
min.put("week", "1");
min.put("year", "2014");
JSONObject max = new JSONObject();
max.put("week", "14");
max.put("year", "2017");
JSONObject json= new JSONObject();
stats.put("min", min);
stats.put("max", max);
System.out.println(json.toString());
Tested this in eclipse already for you.
`
String s = "{ \"min\": { \"week\": \"1\", \"year\": \"2014\" }, \"max\": { \"week\": \"14\", \"year\": \"2017\" } }";
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json.get("min"));
// this will output
//{"week":"1","year":"2014"}
} catch (Exception e){
e.printStackTrace();
}
`
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONObject jsonObject = (JSONObject) obj;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
Following is the JSON String:
{
"Search": {
"VehicleList": [
{
"sipp": "CDMR",
"name": "Ford Focus",
"price": 157.85,
"supplier": "Hertz",
"rating": 8.9
},
{
"sipp": "FVAR",
"name": "Ford Galaxy",
"price": 706.89,
"supplier": "Hertz",
"rating": 8.9
}
]
}
}
}
Hi, I can iterate over the whole JSON object with my code but right now I want to print out the name of a vehicle and the price of the vehicle individually. Any help would be appreciated, I am a beginner when it comes to working with JSON.
Your JSON is structured like this JsonObject -> JsonArray-> [JsonObject]
With that in mind you can access the name and price with this
Object obj = parser.parse(new FileReader("C:/Users/dan/Documents/rental.txt"));
JSONArray jsonArray = (JSONObject) obj.getJsonArray("VehicleList");
for(JSONObject jsonObject : jsonArray){
System.out.println(jsonObject.getString("name") + " " + jsonObject.getDouble("price"))
}
}
Depending on your import library it may deviate from the above but the concept is the same.
You need to iterate over the json. For example.
$.Search.VehicleList[0].price will give you [157.85]
$.Search.VehicleList[1].price will give you [706.89]
http://www.jsonquerytool.com/ will come handy for you :)
Can someone help me with passing below JSON data in body for my HTTP POST call..
{
"name": "ABC",
"user": "fl9f03fe24a2c4a4b51a4d75",
"data":
{
"details": "component",
"Key": "123",
"region": "server-23"
}
}
So this is your code (I edited your post, please accept it):
JSONObject obj = new JSONObject();
obj.put("name", "ABC");
obj.put("user","fl9f03fe24a2c4a4b51a4d75");
datanew = (JSONObject) obj.get("data");
datanew.put("details", "component");
datanew.put("Key", "123");
datanew.put("region","server-23");
Your JSON object obj is new and empty, it doesn't contain anything. So you can't get("data") before you put("data") first. Try this:
JSONObject obj = new JSONObject();
obj.put("name", "ABC");
obj.put("user","fl9f03fe24a2c4a4b51a4d75");
JSONObject datanew = new JSONObject();
datanew.put("details", "component");
datanew.put("Key", "123");
datanew.put("region","server-23");
obj.put("data", datanew);
Is it possible to create and parse json like this
{
"time1": { "UserId": "Action"},
"time2": { "UserId": "Action"},
"time3": { "UserId": "Action"}
}
with json-simple.jar
I would like to keep on updating the json with the element "time": { "UserId": "Action"}
Any help ? please
Yes it's possible just use this to create :
JSONObject obj=new JSONObject();
JSONObject timeObj = new JSONObject();
timeObj.put("UserId", "Action");
obj.put("time", timeObj);
and to parse
Object obj=JSONValue.parse(value);
JSONObject object=(JSONObject)obj;
JSONObject timeObj = obj.get("time");
String action = timeObj.get("UserId");
but I don't recommends you to create JSON with format like that, the JSONObject property key must be unique, I suggest you to use JSONArray instead of JSONObject
I hope this can help you
Your JSON is incorrect. You can't have duplicate time keys. Convert it into a JSON array instead.
{
"time": [
{ "UserId": "Action"},
{ "UserId": "Action"},
{ "UserId": "Action"}
]
}
Here's how you can parse this JSON string
String json =
"{\n" +
" \"time\": [\n" +
" { \"UserId\": \"Action\"},\n" +
" { \"UserId\": \"Action\"}\n" +
" ]\n" +
"}";
JSONObject jsonRoot = new JSONObject(json);
JSONArray timeArray = jsonRoot.getJSONArray("time");
System.out.println(timeArray);
// prints: [{"UserId":"Action"},{"UserId":"Action"}]
Here's how you can add a new object to this JSON array
timeArray.put(new JSONObject().put("Admin", "CreateUser"));
System.out.println(timeArray);
// prints: [{"UserId":"Action"},{"UserId":"Action"},{"Admin":"CreateUser"}]
I am trying to parse json output from neo4j in java as:
Object obj = parser.parse(new FileReader("D:\\neo4j.json"));
JSONArray json = (JSONArray) obj;
System.out.println(json.size());
for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = (JSONObject) json.get(i);
String data = (String);
jsonObject.get("outgoing_relationships");
String name = (String) jsonObject.get("name");
System.out.println(data);
System.out.println(name);
}
Can somebody help me to get values inside "data" element:
I have json output from neo4j as follows:
[{
"outgoing_relationships": "http://host1.in:7474/db/data/node/133/relationships/out",
"data": {
"MOTHERS_NAME": "PARVEEN BAGEM",
"MOBILE_NO": "9211573758",
"GENDER": "M",
"name": "MOHD",
"TEL_NO": "0120-",
"PINCODE": "110001"
},
"traverse": "http://host1.in:7474/db/data/node/133/traverse/{returnType}",
"all_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/all/{-list|&|types}",
"property": "http://host1.in:7474/db/data/node/133/properties/{key}",
"self": "http://host1.in:7474/db/data/node/133",
"properties": "http://lhost1.in:7474/db/data/node/133/properties",
"outgoing_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/out/{-list|&|types}",
"incoming_relationships": "http://host1.in:7474/db/data/node/133/relationships/in",
"extensions": {
},
"create_relationship": "http://host1.in:7474/db/data/node/133/relationships",
"paged_traverse": "http://host1.in:7474/db/data/node/133/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships": "http://host1.in:7474/db/data/node/133/relationships/all",
"incoming_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/in/{-list|&|types}"
}]
Regards,
Jayendra
You can try following way. Inside the for loop get the data node as JSONObject. From that data node you can extract every property. I just extracted mother name from data.
JSONObject data = (JSONObject) jsonObject.get("data");
final String motherName = (String) data.get("MOTHERS_NAME");
What library are you using to parse JSON ? I'd recommend that you use Jackson
For eg: To get the data you read from the file in a Map, you can write a method like this.
#SuppressWarnings("rawtypes")
public static Map toMap(Object object) throws JsonProcessingException{ ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(object, Map.class);
}