Retriving the array values from json string - java

I have a cart array (JavaScript array) in my web application where I store different products. And each product has different specifications (i.e. URL, name, price, quantity, total price) which is again stored in an array.
So it forms an array of arrays. I need to save this cart to a database.
To persist it to database I need to get these arrays in a Java class and then save to database.
How can I take this array to database?
My array which is in json format goes goes like this (dummy array):
{"products":[{"productURL":"images/product/a.jpg","productName":"Headfones 1","productPrice":"234","productQuantity":"2","productTotal":"468"},
{"productURL":"images/product/b.jpg","productName":"Headfones 2","productPrice":"234","productQuantity":"3","productTotal":"702"},
{"productURL":"images/product/d.jpg","productName":"Headfones 4","productPrice":"234","productQuantity":"1","productTotal":"234"},
{"productURL":"images/product/d.jpg","productName":"Headfones 4","productPrice":"234","productQuantity":"6","productTotal":"1404"}]}
any library for parsing json??

Send the JavaScript array in JSON format to the server. Then parse JSON on the server and convert to a Java array. I'd recommend the Jackson JSON parser. This is a working example:
String JSON = "[[\"images/product/a.jpg\",\"Headfones 1\",\"234\",3,702],"
+ "[\"images/product/b.jpg\",\"Headfones 2\",\"234\",4,936],"
+ "[\"images/product/c.jpg\",\"Headfones 3\",\"234\",5,1170]]";
String[][] products = new ObjectMapper().readValue(
JSON,
new TypeReference<String[][]>() {});
With the products array, you can now start writing the data to the database.

Related

how to convert an Item (dynamodbv2.document.Item) object into JSON in java?

i'm implementing a lambda function in aws. i use dynamodb to store data and the application is written using java. the function is getting item from dynamodb and returns it as response. i want to return its values as JSON for the response. i use the following code but it returns {"empty:false"} in aws lambda test. but when i return it as String it prints the values. but i need it in Json.
Table table = dynamoDb.getTable(DYNAMODB_TABLE_NAME);
Item searchedItem = table.getItem("name", input.getName());
String name = searchedItem.getString("name");
int count = searchedItem.getInt("count");
MapjsonMap=new HashMap<>();
jsonMap.put("name",name);
jsonMap.put("count",count);
JSONObject json = new JSONObject(searchedItem.toJSONPretty());
for (String key:jsonMap.keySet()) {
json.put(key,jsonMap.get(key));
}
return json;
i expect the result to contain the values of dynamodb and it returns {"empty":false}.
finaly i got fixed the problem. the aws lambda is auto converting java model objects and json. no need to do it manually by us :-D just return the result in a corresponding java POJO object and you'll get the Json output in aws. thanks everyone for commenting. cheers.

retrieve json is in wrong format in java

I want retrieve json from postgres sql and I will convert it to a plain string.
I want full json with json String.
DeviceProfile dp = device.getDp();
System.out.println("parameters Data:: "+dp.getParameters().toString());
JSONObject parameters = new ObjectMapper().readValue(dp.getParameters().toString(),JSONObject.class);
It will print following String which is wrong.
{Rs232=[{rs232unit=, parameterId=6, rs232ioindex=1.0, parametername=rs232}], Digital=[{reverse=true, dioindex=1.0, parameterId=1, parametername=Ignition}]}
I want proper json.
I am using jsckson api to parse data.
See database Screen Short

How to get up-to-date data from dynamically updated json?

There's a chat which content I want to parse. I got the url to get the .json of it. So it looks like:
{"messages":[
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"}
]}
But this json has some limitation, I think approximately 20-30 records. New records are added at the beginning. It looks like:
{"messages":[
{"id":"222222","uid":"33333","name":"User","message":"Message","date":"2013-02-15 18:21:59","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:55","chatId":"111"}
]}
.......
{"messages":[
{"id":"333333","uid":"44444","name":"User","message":"Message","date":"2013-02-15 19:13:34","chatId":"111"},
{"id":"222222","uid":"33333","name":"User","message":"Message","date":"2013-02-15 18:21:59","chatId":"111"},
{"id":"111111","uid":"22222","name":"User","message":"Message","date":"2013-02-15 17:21:54","chatId":"111"}
]}
I gonna read this json via GSON or JSON Java and place to any output, it doesn't matter :)
But is there any best-practices on how to parse new records in dynamically updated json? In fact I don't know how to control that it is updated, but reading it every second and put results to output will result in data duplication I think.
You will need to slice this data some way... To not make your GSON parse slow when your file grows, I think you would need to preprocess your file, slicing the disposable data. I would do something like:
First execution: parse the file entirely and store the first id, since it is the newest data;
Second execution (and others): read the file and store it in a StringBuilder. Using the String obtained, slice the disposable data, since you have the id stored prior. This id will show you where you need to start your slicing. With the new data, parse the GSON and stores the first id again.
You may use this create your code to perform the slicing and adapt to the idea that I said below:
String data = "{\"messages\":[" +
"{\"id\":\"333333\",\"uid\":\"44444\",\"name\":\"User\",\"message\":\"Message\",\"date\":\"2013-02-15 19:13:34\",\"chatId\":\"111\"}," +
"{\"id\":\"222222\",\"uid\":\"33333\",\"name\":\"User\",\"message\":\"Message\",\"date\":\"2013-02-15 18:21:59\",\"chatId\":\"111\"}," +
"{\"id\":\"111111\",\"uid\":\"22222\",\"name\":\"User\",\"message\":\"Message\",\"date\":\"2013-02-15 17:21:54\",\"chatId\":\"111\"}" +
"]}";
String lastId = "111111";
int sliceUntil = data.indexOf( "{\"id\":\"" + lastId + "\"" );
// since your disposable data is in the "tail" you your file,
// you just need to get the valid data (the data until the "last id")
// and add the chars "]" and "}" to close your JSON
String newData = data.substring( 0, sliceUntil ) + "]}";
System.out.println( newData );
You have uniq "date" for every message, so you can just create Map<Date, Message>, update it with all non-existant elements. Or you can just use Map<String, Message> with date string if you don't need time sorting

how to search a JSONArray inside the JSONObject in JAVA

I have a JSONObject which inturn contains two JSONObjects ( key is rows_map and columns_map)
{
"rows_map":{
"3":["Test","Test","Test","Test","Test",null,null,null,null,null,"2011-10-07 15:47:56.0",null,null],
"2":["test","","","","",null,null,null,"123456789","123456789.user","2011-10-07 12:49:49.0",null,null]
},
"columns_map":{
columns_map":"fld1","fld2","fld3","fld4","fld5","Latitude","Longitude","Altitude","Mobile Number","Name","Time","Message","Advertisment"]
}
}
In rows_map 3 and 2 are record numbers.
Each record is related to columns in columns_map.
I want to get records list based on mobile number column
for eg: recordslist of mobilenumber equal to 123456789
How can i do this.
In the case that you're trying to read a json using java, you should be parsing it as an object rather than via syntax. Take a look at:
https://stackoverflow.com/questions/338586/a-better-java-json-library

Parse JSON record to extract key and value and put into Map in java

I have one column in my table which will store data in string format the sample data is
{"pre-date":{"enable":true,"days":"3","interval":"1","mail-template":"582"},"on-date":{"enabled":false},"post-date":{"enabled":false}}
and the string contains data like json data
but when i will send this record for controller to view it should be in format
enable : true
days : 3
interval : 1
so that i can set values to respective form elements how to do this in java any help
Read the complete JSON string from the database, then parse it using a JSON parser, and extract the information you're interested into from the data structure/object returned from the parsing.
There are lots of JSON parsers available. Look at this page, which lists a number of them in the Java section (you have to scroll a little bit down).
Jackson provides the best support for simple conversion of any JSON object into a Java Map comprised of only Java SE components.
Following is an example using the JSON from the original question.
// {"pre-date":{"enable":true,"days":"3","interval":"1","mail-template":"582"},"on-date":{"enabled":false},"post-date":{"enabled":false}}
String json = "{\"pre-date\":{\"enable\":true,\"days\":\"3\",\"interval\":\"1\",\"mail-template\":\"582\"},\"on-date\":{\"enabled\":false},\"post-date\":{\"enabled\":false}}";
ObjectMapper mapper = new ObjectMapper();
// To put all of the JSON in a Map<String, Object>
Map<String, Object> map = mapper.readValue(json, Map.class);
// Accessing the three target data elements
Map<String, Object> preDateMap = (Map) map.get("pre-date");
System.out.println(preDateMap.get("enable"));
System.out.println(preDateMap.get("days"));
System.out.println(preDateMap.get("interval"));

Categories

Resources