I am getting the String in following format which is causing problem while parsing using Jackson ObjectMapper readTree api. Code used to parse the given String is
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
JsonNode rootNode = objectMapper.readTree(inputString);
It is throwing exception when it encounters "7" in the below String
{
OBJECT_CONVERSION_ERROR:"Failed..."
Portal:{
7061:"User is....."}
}
How to convert such a String in Valid JSON format using JAVA ?
I am using jackson-all-1.9.11.jar
Below is my exception message
org.codehaus.jackson.JsonParseException: Unexpected character ('7' (code 55)): was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name
at [Source: java.io.StringReader#3fb1549b; line: 1, column: 1433]
Is there any way to convert the input String in valid json format before passing it to Object Mapper for parsing it ?
The Jackson ObjectMapper expects double-quoted field names in its default configuration.
To change this behavior you could do the following:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
JSONParser parser = new JSONParser(); JSONObject json = (JSONObject)
parser.parse(stringToParse);
Read more: http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html#ixzz4y2fACQlg
Related
I am trying to extract a value of predefined type (Boolean, Integer, joda.DateTime) from an arbitrary json that is sent as a String.
Eg: {"node1":{"node2":"2019-01-01T05:00:00.000Z"}}} and say I know that the value in this Json is a DateTime and I can extract the value 2019-01-01T05:00:00.000Z from this Json and disabled SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.
When I try to serialize a simple String representation "1972-12-28T12:00:01.000Z" of org.joda.time.DateTime, it fails with JsonParseException: Unexpected character. However serialization will succeed for Booleans or DateTime string inside a TextNode.
I have have registered com.fasterxml.jackson.datatype.joda.JodaModule with my object mapper.
I have tried a few things, see the Junit test below
public class Tester {
public static class Bean {
public void Bean(){}
public DateTime start;
}
#Test
public void testJodaJsonSerialization() throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.registerModule(new JodaModule());
final String INPUT_JSON = "{\"start\" : \"1972-12-28T12:00:01.000Z\"}";
Bean bean = objectMapper.readValue(INPUT_JSON, Bean.class);
assertNotNull(bean.start);
System.out.println(objectMapper.writeValueAsString(bean)); //serializing as part of an object works
String boolAsString = "true";
Boolean aBoolean = objectMapper.readValue(boolAsString, Boolean.class); //works for bool (simple type)
System.out.println(aBoolean);
String dateAsTextNode = objectMapper.writeValueAsString(new TextNode("1972-12-28T12:00:01.000Z")); //works for TextNode
System.out.println("dateAsTextNode: " + dateAsTextNode);
DateTime dateTime = objectMapper.readValue(dateAsTextNode, DateTime.class);
System.out.println(dateTime);
JsonNode jsonRoot = objectMapper.readTree(INPUT_JSON);
String datetimeAsString = jsonRoot.get("start").asText();
objectMapper.readValue(objectMapper.writeValueAsString(new TextNode(datetimeAsString)), DateTime.class); //this workaround will work
objectMapper.readValue(objectMapper.writeValueAsString(new TextNode(boolAsString)), Boolean.class);
String dateAsString = "1972-12-28T12:00:01.000Z";
objectMapper.readValue(dateAsString, DateTime.class); //but this fails
}
}
I expect String serialization to work just like it does on the TextNode
Your String
String dateAsString = "1972-12-28T12:00:01.000Z";
contains the content
1972-12-28T12:00:01.000Z
which is not valid JSON, so Jackson cannot parse it.
It would be valid JSON if it contained leading quotes, so
String dateAsString = "\"1972-12-28T12:00:01.000Z\"";
and then parsing would succeed.
You can configure the pattern of the date format on the ObjectMapper level:
Value dateFormat = Value.forShape(Shape.STRING)
.withPattern("MM/dd/yyyy HH:mm:ss")
.withTimeZone(TimeZone.getTimeZone("UTC"));
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.configOverride(DateTime.class).setFormat(dateFormat);
This question already has answers here:
Make Jackson interpret single JSON object as array with one element
(3 answers)
Closed 4 years ago.
I am trying to parse JSON data using Jackson, found that instance some time as array or String
JSON DATA instance with String :
{
"Value" : "1"
}
JSON DATA instatnce with Array :
{
"Value" : ["ram","kumar"]
}
due to this getting error are given below
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of `java.util.ArrayList` out of VALUE_STRING token
In this case how to solve this,thankyou
current java code
ObjectMapper objectMapper = new ObjectMapper();
try {
String jsonInString = objectMapper.writeValueAsString(products.get(j));
InventoryParser inventoryParser =
objectMapper.readValue(jsonInString, InventoryParser.class);
System.out.println(inventoryParser.getName());
}
catch (IOException e)
{
e.printStackTrace();
}
}
Read into a map data structure like so and then process it.
final Map<String, Object> result = new ObjectMapper().readValue(jsonStr,
new TypeReference<Map<String, Object>>() {
});
You can write a custom deserializer and write custom logic to handle such data. In the deserializer you can check whether the node is an array or not.
Please refer deserialize xml to pojo using jackson xml mapper (The example is in XML but can be similarly used for JSON too by using ObjectMapper)
Are there any libraries to convert JSON in String/jackson/org.JSON.JSONOBJECT/etc... to a JSON schema?
So far, the only generator I found covert Java classes to JSON schemas. I'm about to write my own converted, but it'd be nice if I didn't have to re-invent the wheel.
looks like there isn't. I had to write my own generator.
Yes there is: https://github.com/java-json-tools/json-schema-validator. It ingests Jacson's JsonNode containing the schema definition and can validate JSON data against that schema.
You can use GSON library.
Convert Java object to JSON:
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON, and save into a file
gson.toJson(obj, new FileWriter("D:\\file.json"));
// 2. Java object to JSON, and assign to a String
String jsonInString = gson.toJson(obj);
Convert JSON to Java object:
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'foo'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);
i got problems when i try to parse json with ObjectMapper and in the json there is an number that look like mate
json
{ "_id" : 290365351583, "my_number" : 1.5638694276102368E8 }
my code
ObjectMapper objectMapper= new ObjectMapper();
DBobject obj = ;\\the json when i select it from mongo db
String data = JSONSerializers.getStrict().serialize(obj);
JsonNode = objectMapper.readTree(data);
when i run this code i got ERROR "Non-standart token 'Infinity': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"
You can use this maven dependency : http://mvnrepository.com/artifact/org.json/json/20160212
It's very simple to understated and use.
ex:
JSONObject obj = "YOUR_JSON_STRING";
String result = obj.getString("YOUR_STRING_KEY");
There you can use alot of methods like: getInt(), getDouble(), getBoolean() etc.
Useful examples are there : http://crunchify.com/java-how-to-parse-jsonobject-and-jsonarrays/
I am trying to read an object into my model using objectMapper
ObjectMapper objectMapper = new ObjectMapper();
result = objectMapper.readValue(process.getData(), params.class);
under one of the keys of params there is a string
href=\"${organizationParams.get(\"info.facebook\")}\">
so after readValue happens the string looks like
href="${organizationParams.get("info.facebook")}">
and then later on I have call to Jsoup.clean() which truncates the string to
href="${organizationParams.get("
This is not desirable. Any ideas on how to retain the string after Jsoup.clean?