I am parsing a json file that contains values that are comma separated.
Such as {"values":[{"key":"some, value", "key2":"somevalue"}]}
When parsing this using the org.json library it is using the commas in the first key as a delimiter so it is parsing them as separate objects.
JSONTokener tokener = new JSONTokener(new FileReader(someJsonFile));
JSONObject a = new JSONObject(tokener);
//I believe the problem is occuring here
JSONArray values = (JSONArray) instruments.get("values");
I want the values that include commas to be treated as one value. Instead of being parsed into 'some' and 'value', i want it to be 'some, value' as indicated in the file.
You should create a POJO class that is equivalent to the JSon String format. Then you can use jackson to convert the JSon string to pojo objects. It will not have the mentioned issue.
Reference : https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Related
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
In Java, using the Jackson ObjectMapper, I'm trying to deserialize a dynamo db object being read from a dynamo db stream.
I first call:
record.getDynamodb().getNewImage().get("primaryKey").getS().toString()
to get the primaryKey value of "1_12345" back from the stream.
I then use it in the object mapper to create a new instance of the Metrics object with the primaryKey member set:objectMapper.readValue("1_12345", Metrics.class);
The problem is I get an exception on that call:
Unexpected character ('_' (code 95)): Expected space separating root-level values
Metrics.class is a simple POJO with no constructor. I'm wondering if I need any special annotations or escape characters in my readValue call. I can't seem to find any clear indications on what the solution is in the case of this error.
(Side note - the reason I can't parse it straight from the json is because the json's structure when it's parsed from the stream isn't straightforward, a value looks like this, S indicating String, N for number etc:
{primaryKey={S: 1_12345,}, rangeKey={N: xxx}... etc. })
Thank you, that was the problem, the readValue() call takes a String in the format of JSON. The solution was to convert the dynamo streamed image into lists & maps (using the dynamodbv2 libs) until it was in the correct format as below:
Map<String, AttributeValue> newImage = record.getDynamodb().getNewImage();
List<Map<String, AttributeValue>> listOfMaps = new ArrayList<Map<String, AttributeValue>>();
listOfMaps.add(newImage);
List<Item> itemList = InternalUtils.toItemList(listOfMaps);
for (Item item : itemList) {
String json = item.toJSON();
Metrics metric = objectMapper.readValue(json, Metrics.class);
}
I'm unable to parse escaped json string through JSONObject, while trying to parse it, I always get an Unterminated Object error. But when I manually remove all of the escape characters from the json string, JSONObject parses it successfully.
But the problem is that for complex or nested json strings, I don't want to remove escape characters, because for nested structures, unescaping the characters results in an invalid json string.
This is the json string after removing escapes characters and I get unterminated object error due to invalid json when parsing through JSONObject
{"result":"unknown","message":"{"firebase":"unknown"}","sender":"unknown"}
This is the unescaped json string
{"result":"unknown","message":"{\"firebase\":\"unknown\"}","sender":"unknown"}
If you look at the json you are constructing it in wrong format.
In case of escaped json
{
"result":"unknown",
"message":"{"firebase":"unknown"}",
"sender":"unknown"
}
the json object "message" is having value "{" and firebase is causing exception.
In the the escaped json "message":{"firebase":"unknown"} will form valid json.
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.
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"));