retrieve json is in wrong format in java - 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

Related

How to change JSON value's datatype as per the JSON Schema?

I have a JSON which is converted from xml. (XML to JSON)
But the converted JSON file has some datatype issue, which is not matched with the expected JSON schema
For ex: expected is accountId: "123" (in Json schema type is mentioned as String)
But actual result is accountId: 123 (it received as a number)
While converting XML to JSON (StAXON parse) makes like this, yes offcourse I didn't feed any datatype related parameters while converting XML to JSON.
From here I have two questions:
Is there any way to resolve my issue while xml to json convertion itself
Or else from my Json, I need to validate with Json schema and change the datatype accordingly.
Guide me to do this in better way.
Feel free to edit the question as my text is not understandable/misleading.
Note: I am using Spring Integration!!!

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.

Retriving the array values from json string

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.

Reading Json String using Gson results error "not a JSON Array"

In my project i have a complex json response. I want to read it by GSon.
JSON : {'FoodMenuRS':{'Results':[{'Items':{'Item':[{'#Id':'24'},{'#Id':'24'}]}}, {'Items':{'Item':{'#Id':'24'}}}]}}
It contains a JSONArray with first "Item" and JSONObject with second one. Hence its call results in error,
failed to deserialize json object {"#Id":"24"} given the type java.util.List<com.servlet.action.ItemInfo> and java.lang.IllegalStateException: This is not a JSON Array.
Please help how i should handle this scenario. Thanks.
The string you are showing is a JSONObject not a JSONArray. So, in this case you first of all have to get the JSONObject and perform further decoding on that JSONObject.
JSONObject - {}
JSONArray - []
And indeed JSONObject or JSONArray should be encoded using Double-quotes(")
Your JSON is valid, but not for the doble quotes (") because JSON supports simple quotes (') and no quotes in the key name. See http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Colle
However this JSON have key names that begin with #. For JSON strings this character is valid at the beginning of the name (see right column http://www.json.org/) but for Java this names are illegal (see Naming section http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html). Specifically, names started with # are annotations and you can't use annotations tags to declare variables, fields, methods, etc.
This is not a valid JSON object. Strings in JSON are always encapsulated in double quotes ("). Contact the producer of that JSON and tell him to use a correct encoder.

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