Convert nested JSON string to list of java object - java

I have this json String
{"data":"[Level [key=LevelKey [keyEnd=0], Description=abc], Level [key=levelKey [keyEnd=1], Description=xyz]", "id":"123"}
And corresponding java classes are
public class Level {
public LevelKey key;
public String id;
}
public class LevelKey{
public String keyEnd;
}
I want to convert this data json string to list of Level object using Jackson
ObjectMapper mapper = new ObjectMapper();
List<Level> arr = mapper.readValue(data, new TypeReference<List<Level>>(){});
But I am getting below error
com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Level': was expecting ('true', 'false' or 'null')
Is there any other method to parse it?

The below does not look like a proper JSON for the purpose (except for a standard fixed string)
"[Level [key=LevelKey [keyEnd=0], Description=abc], Level [key=levelKey [keyEnd=1], Description=xyz]"
You could correct the data part of your JSON to something like below (Closest to your JSON in question) :
[\"Level [key=LevelKey [keyEnd=0], Description=abc]\",\" Level [key=levelKey [keyEnd=1], Description=xyz]\"]
Is there any other method to parse it?
You could use a direct class reference of ArrayList instead of having to instantiate TypeReference like below to parse the above (corrected) json string :
List<Level> arr = mapper.readValue(data, (new ArrayList<Level>()).getClass());

This was an interesting one I must say. Take a look at code snippet I think I got it correct :
String data ="{\"data\":\"[Level [key=LevelKey [keyEnd=0], Description=abc], Level [key=levelKey [keyEnd=1], Description=xyz]\", \"id\":\"123\"}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<Level> arr = mapper.readValue(data, (new ArrayList<Level>()).getClass());
System.out.println(arr);
I got the following output :
[{data=[Level [key=LevelKey [keyEnd=0], Description=abc], Level [key=levelKey [keyEnd=1], Description=xyz], id=123}]
Also if you encountered any JsonParseException which according to documentation means :
Exception type for parsing problems, used when non-well-formed content
(content that does not conform to JSON syntax as per specification) is
encountered.
So while hacking the JSON you can update the ObjectMapper object like this :
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
Also as mentioned by Exception_al using a direct class reference of ArrayList instead of having to instantiate TypeReference like below to parse the above (corrected) json string.
List<Level> arr = mapper.readValue(data, (new ArrayList<Level>()).getClass());
Hope this helped.

The String is not the JSON representation of what you expect you get deserialized into JAVA.
This is a JSON String:
"{"data":[{"key":{"keyEnd":0},"Description":"abc"},{"key":{"keyEnd":1},"Description":"abc"}],"id":"123"}"
So, there is either a problem with the String or you need to do the parsing yourself.

Related

Why parsing Invalid json returns Empty Object [duplicate]

I need GSON mapper to throw an exception if json contains unknown fields. For example if we have POJO like
public class MyClass {
String name;
}
and json like
{
"name": "John",
"age": 30
}
I want to get some sort of message that json contains unknown field (age) that can not be deserialized.
I know there is out-of-box solution in Jackson mapper, but in our project we have been using Gson as a mapper for several years and using Jackson ends up in conflicts and bugs in different parts of project, so it is easier for me to write my own solution than using Jackson.
In other words, I want to know if there is some equivalent to Jackson's DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES in Gson. Or maybe if it can be done using Gson's DeserializationStrategy other than using reflections
I believe you cannot do it automatically with Gson.
I had to do this in a project at work. I did the following:
Gson GSON = new GsonBuilder().create();
(static final) Map<String, Field> FIELDS = Arrays.stream(MyClass.class.getDeclaredFields())
.collect(Collectors.toMap(Field::getName, Function.identity()));
JsonObject object = (JsonObject) GSON.fromJson(json, JsonObject.class);
List<String> objectProperties = object.entrySet().stream().map(Entry::getKey).collect(Collectors.toList());
List<String> classFieldNames = new ArrayList<>(FIELDS.keySet());
if (!classFieldNames.containsAll(objectProperties)) {
List<String> invalidProperties = new ArrayList<>(objectProperties);
invalidProperties.removeAll(classFieldNames);
throw new RuntimeException("Invalid fields: " + invalidProperties);
}

Converting malformed json array string to Java object

I have a malformed json array string which I get from an API call as follows:
[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Processed successfully\"}]\"}]
There is a double quote before open square bracket in the value of Response Msg property.
Is there a way to convert this into Java object ?
What I have tried so far:
I have used Jackson to parse it as follows but it gives error
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new ResponseNameStrategy());
Response[] response = mapper.readValue(strOutput1, Response[].class);
Error: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
I have also tried using Gson to parse it but it also gives error
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
Response[] response = gson.fromJson(strOutput1, Response[].class);
Error: Expected BEGIN_ARRAY but was STRING at line 1 column 35 path $[0].ResponseMsg
I have gone through the following links on StackOverflow but none of them has addressed my issue:
How to Convert String Array JSON in a Java Object
Convert a JSON string to object in Java ME?
JSON Array to Java objects
Convert json String to array of Objects
converting 'malformed' java json object to javascript
I think the answer is in the comments, you appear to be trying to solve the issue on the wrong place.
You are receiving json which you wish to parse into java objects, unfortunately the json is malformed so will not parse.
As a general rule you should never be trying to solve the symptom, but should look for the root cause and fix that, it may sound trivial but fixing symptoms leads to messy, unpredictable, and unmaintainable systems.
So the answer is fix the json where it is being broken. If this is something or of your control, while you wait for the fix, you could put a hack in to fix the json before you parse it.
This way you won't compromise your parsing, and only have a small piece of string replacement to remove when the third party has fixed the issue. But do not go live with the hack, it should only be used during development.
As i mentioned in the comment, you should prepare your service response in order to parse it.
I implemented an example:
public class JsonTest {
public static void main(String args[]) throws JsonProcessingException, IOException{
String rawJson =
"[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Processed successfully\"}]\"}]";
String goodJson = "{"+rawJson.split("[{{.}]")[2]+"}";
ObjectMapper mapper = new ObjectMapper();
final ObjectNode node = mapper.readValue(goodJson, ObjectNode.class);
System.out.println("Pretty Print: " + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));
System.out.println("Just code: " + node.get("Code"));
}
}
Which returns:
This is how I finally solved my issue:
String inputJsonStr = "[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Claim has been added successfully.\"}"
+ "]\"}]";
int indexOfRes = inputJsonStr.indexOf("ResponseMsg");
if(inputJsonStr.substring(indexOfRes+13,indexOfRes+14).equals("\""))
{
inputJsonStr = inputJsonStr.substring(0,indexOfRes+13) + inputJsonStr.substring(indexOfRes+14);
}
int indexOfFirstClosingSquare = inputJsonStr.indexOf("]");
if(inputJsonStr.substring(indexOfFirstClosingSquare+1, indexOfFirstClosingSquare+2).equals("\"")) {
inputJsonStr = inputJsonStr.substring(0, indexOfFirstClosingSquare+1)+inputJsonStr.substring(indexOfFirstClosingSquare+2);
}
Now inputJsonStr contains a valid json array which can be parsed into Java custom object array easily with gson as given in this SO link:
Convert json String to array of Objects

String deserialization and conversion to JSON in Java

After deserializing my string and converting it to JSON using the code below:
JSONObject returnValue = new JSONObject();
String toJson = null;
try
{
Object otherObjectValue = SerializationUtils
.deserialize(myBytesArray);
Gson gson = new Gson();
toJson = gson.toJson(otherObjectValue);
returnValue.put(key, toJson);
}
some part of the JSON still has something like:
{ "key":"ATTRIBUTE_LIST", "value":"{\"attributeContract\":[{\"scope\":\"sso\",\"name\":\"SAML_SUBJECT\",\"description\":\"Click to Edit\",\"required\":true}]}"}
which means everything in:
"{\"attributeContract\":[{\"scope\":\"sso\",\"name\":\"SAML_SUBJECT\",\"description\":\"Click to Edit\",\"required\":true}]}"
is one string instead being another object with fields. Is there something I can do to sanitize by JSONObject to make it properly JSON?
The key part is OK, means the whole String is JSON formatted.
For the value part, /shows that the value of value is JSON formatted already.
So you may "deserialize" the value of value again to retrieve an Object result. Or you may ask the creator of origin JSON, to serialize origin Object one time into JSON format.

Add a property to a json string with jackson json

I am storing a json string into a text field in mysql.
After the insertion, i want to update my json string and add the mysql line id into it with jackson json.
I have a java String which is in Json format
{
"thing":"val"
}
I'm looking to add another K/V without writing lines of codes.
to finally have this :
{
"thing":"val"
"mysqlId":10
}
I can convert my String to a JsonNode :
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree( jsonStr);
Looking to do something like this
json.put("mysqlId",10);
json.toString();
then update in my text field with new json string in mysql
I can't make it.
I don't want use many class is there a simple way to do so with jackson?
Try casting your JsonNode to an com.fasterxml.jackson.databind.node.ObjectNode and then calling put set (or replace) on it.

In XStream is there a better way to marshall/unmarshall List<Object>'s in JSON and Java

I'm using XStream and JETTISON's Stax JSON serializer to send/receive messages to/from JSON javascripts clients and Java web applications.
I want to be able to create a list of objects to send to the server and be properly marshalled into Java but the format that XStream and JSON expect it in is very non-intuitive and requires our javascript libraries to jump through hoops.
[EDIT Update issues using GSON library]
I attempted to use the GSON library but it cannot deserialize concrete objects when I only have it expect generic super classes (XStream and Jettison handles this because type information is baked into the serialization).
GSON FAQ states Collection Limitation:
Collections Limitations
Can serialize collection of arbitrary objects but can not deserialize from it
Because there is no way for the user to indicate the type of the resulting object
While deserializing, Collection must be of a specific generic type
Maybe I'm using bad java practices but how would I go about building a JSON to Java messaging framework that sent/received various concrete Message objects in JSON format?
For example this fails:
public static void main(String[] args) {
Gson gson = new Gson();
MockMessage mock1 = new MockMessage();
MockMessage mock2 = new MockMessage();
MockMessageOther mock3 = new MockMessageOther();
List<MockMessage> messages = new ArrayList<MockMessage>();
messages.add(mock1);
messages.add(mock2);
messages.add(mock3);
String jsonString = gson.toJson(messages);
//JSON list format is non-intuitive single element array with class name fields
System.out.println(jsonString);
List gsonJSONUnmarshalledMessages = (List)gson.fromJson(jsonString, List.class);
//This will print 3 messages unmarshalled
System.out.println("XStream format JSON Number of messages unmarshalled: " + gsonJSONUnmarshalledMessages.size());
}
[{"val":1},{"val":1},{"otherVal":1,"val":1}]
Exception in thread "main" com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter#638bd7f1 failed to deserialized json object [{"val":1},{"val":1},{"otherVal":1,"val":1}] given the type interface java.util.List
Here's an example, I want to send a list of 3 Message objects, 2 are of the same type and the 3rd is a different type.
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
class MockMessage {
int val = 1;
}
class MockMessageOther {
int otherVal = 1;
}
public class TestJSONXStream {
public static void main(String[] args) {
JettisonMappedXmlDriver xmlDriver = new JettisonMappedXmlDriver();
XStream xstream = new XStream(xmlDriver);
MockMessage mock1 = new MockMessage();
MockMessage mock2 = new MockMessage();
MockMessageOther mock3 = new MockMessageOther();
List messages = new ArrayList();
messages.add(mock1);
messages.add(mock2);
messages.add(mock3);
String jsonString = xstream.toXML(messages);
//JSON list format is non-intuitive single element array with class name fields
System.out.println(jsonString);
List xstreamJSONUnmarshalledMessages = (List)xstream.fromXML(jsonString);
//This will print 3 messages unmarshalled
System.out.println("XStream format JSON Number of messages unmarshalled: " + xstreamJSONUnmarshalledMessages.size());
//Attempt to deserialize a reasonable looking JSON string
String jsonTest =
"{"+
"\"list\" : ["+
"{"+
"\"MockMessage\" : {"+
"\"val\" : 1"+
"}"+
"}, {"+
"\"MockMessage\" : {"+
"\"val\" : 1"+
"}"+
"}, {"+
"\"MockMessageOther\" : {"+
"\"otherVal\" : 1"+
"}"+
"} ]"+
"};";
List unmarshalledMessages = (List)xstream.fromXML(jsonTest);
//We expect 3 messages but XStream only deserializes one
System.out.println("Normal format JSON Number of messages unmarshalled: " + unmarshalledMessages.size());
}
}
Intuitively I expect the XStream JSON to be serialized (and able to deserialize correctly) from the following format:
{
"list" : [
{
"MockMessage" : {
"val" : 1
}
}, {
"MockMessage" : {
"val" : 1
}
}, {
"MockMessageOther" : {
"otherVal" : 1
}
} ]
}
Instead XStream creates a single element list with fields that are named the classnames and nested arrays of Objects of the same type.
{
"list" : [ {
"MockMessage" : [ {
"val" : 1
}, {
"val" : 1
} ],
"MockMessageOther" : {
"otherVal" : 1
}
} ]
}
The trouble may be caused by it using the XStream XML CollectionConverter?
Does anyone have a suggestion for a good JSON Java object serialization that allows you to read/write arbitrary Java objects. I looked at the Jackson Java JSON Processor but when you were reading in objects from a stream you had to specify what type of object it was unlike XStream where it will read in any object (because the serialized XStream JSON contains class name information).
I agree with other poster in that XStream is not a good fit -- it's an OXM (Object/Xml Mapper), and JSON is handled as a secondary output format using XML processing path. This is why a "convention" (of how to convert hierarchich xml model into object-graph model of json and vice versa) is needed; and your choice boils down to using whatever is least intrusive of sub-optimal choices.
That works ok if XML is your primary data format, and you just need some rudimentary JSON(-like) support.
To get good JSON-support, I would consider using a JSON processing library that does real OJM mapping (I assume Svenson does too, but additionally), such as:
Jackson
Google-gson
Also: even if you do need to support both XML and JSON, you are IMO better off using separate libraries for these tasks -- objects (beans) to use on server-side need not be different, just serialization libs that convert to/from xml and json.
I realize this is off-topic, but I'd like to present a solution in svenson JSON.
Do you really need public fields in your domain classes? Apart from having to use properties, svenson can handle cases like this with a more simple JSON output with a discriminator property
class Message
{
// .. your properties with getters and setters ..
// special property "type" acts a signal for conversion
}
class MessageOther
{
...
}
List list = new ArrayList();
list.add(new Message());
list.add(new MessageOther());
list.add(new Message());
String jsonDataSet = JSON.defaultJSON().forValue(list);
would output JSON like
[
{"type":"message", ... },
{"type":"message_other", ... },
{"type":"message", ... }
]
which could be parsed again with code like this
// configure reusable parse instance
JSONParser parser = new JSONParser();
// type mapper to map to your types
PropertyValueBasedTypeMapper mapper = new PropertyValueBasedTypeMapper();
mapper.setParsePathInfo("[]");
mapper.addFieldValueMapping("message", Message.class);
mapper.addFieldValueMapping("message_other", MessageOther.class);
parser.setTypeMapper(mapper);
List list = parser.parse(List.class, jsonDataset);
A svenson type mapper based on the full class name would look something like this
public class ClassNameBasedTypeMapper extends PropertyValueBasedTypeMapper
{
protected Class getTypeHintFromTypeProperty(String value) throws IllegalStateException
{
try
{
return Class.forName(value);
}
catch (ClassNotFoundException e)
{
throw new IllegalStateException(value + " is no valid class", e);
}
}
}
which is not an ideal implementation as it inherits the configuration of PropertyValueBasedTypeMapper without really needing. (should include a cleaner version in svenson)
The setup is very much like above
JSONParser parser = new JSONParser();
ClassNameBasedTypeMapper mapper = new ClassNameBasedTypeMapper();
mapper.setParsePathInfo("[]");
parser.setTypeMapper(mapper);
List foos = parser
.parse( List.class, "[{\"type\":\"package.Foo\"},{\"type\":\"package.Bar\"}]");

Categories