Simple json like this. creating and parsing - java

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"}]

Related

How to store json data in String varaiables?

How to store json data in String variables. I tried but it is showing an error.I want to store below json in one normal string.I tried lot it's always showing error.
[
{
"order":0,
"name":"expenseType",
"required":true,
"type":"text",
"placeholder":"Expense Type"
},
{
"order":1,
"name":"date",
"required":true,
"type":"text",
"placeholder":"Expense Date"
},
{
"order":3,
"name":"amount",
"required":true,
"type":"number",
"placeholder":"Enter Amount"
},
{
"order":4,
"name":"description",
"required":true,
"type":"text",
"placeholder":"Description"
},
{
"order":5,
"name":"imageUrls",
"type":"fileUpload",
"options":[ urls:string]
}
]
Error: org.json.JSONException: Unterminated array at character 641
Just use toString() on JsonObject.
String jsonString=jsonObject.toString();
Rcreate Json Object from String .
JSONObject jsonObject=new JSONObject(jsonString);
If you want Json String as constant then just paste it beetween double quotes. Example json .
{
"token":"",
"type":"1",
"message":{
"type":1,
"message":"message"
}
}
And as String it is.
String jsonString ="{\n" +
" \"token\":\"\",\n" +
" \"type\":\"1\",\n" +
" \"message\":{\n" +
" \"type\":1,\n" +
" \"message\":\"message\"\n" +
" }\n" +
"}";
you can use GSON , create your object class
Gradle :
compile 'com.google.code.gson:gson:2.8.2'
Java :
Gson gson = new Gson();
String myJson = "my string json array";
List<Object> list= gson.fromJson(myJson,new TypeToken<List<Object>>(){}.getType());
See the Documentation

How to create multi level JSON data using JSONObject in servlet

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();
}
`

Parsing and retrieving elements in a JSON Java

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 :)

Removing simple object from JSON request

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);

How to decode JSONObject

This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}

Categories