1

I have a class pojo class

class A{

    private List<String> colors;

    // getters and setters.


}

The data comes in json format.

Data coming from database is ---- A {"colors":""}

The data should come in -- A{"colors":["red"]}.

The problem here is, java cann't convert data {"colors":""} which in string to array {"colors":["red"]} .Because of this I am getting InputMismatchException.

Is there any way to convert {"colors":""} to {"colors":["red"]} ?

I want to know how to handle this in java.

I am using jackson parser for converting json to java object.

Sasidhar
  • 111
  • 1
  • 1
  • 7
  • 1
    Can you update your question with some effort or at least tell are you using Gson, Jackson or some other to deserialize? I'm pretty sure that java can do it if you code it but I guess you mean your deserializer can not do it automatically? – pirho Sep 16 '18 at 10:15
  • I am using jackson parser for mapping json to java pojo. – Sasidhar Sep 16 '18 at 14:02

1 Answers1

1

What you want is basically loading the colors from a json file. Let's assume that json file is called "colors.json". What you should do, is use one of existing third party java libraries that can read from a file and work with json objects. For example, you could use "org.json.simple" library. Example can be found here: https://www.mkyong.com/java/json-simple-example-read-and-write-json/

After reading the file "colors.json" into the JSONParser, you will get a JSONObject. Using this object you can get the colors list by writing:

JSONArray colors = (JSONArray) obj.get("colors");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
   String color = (String) iterator.next();
   // add color to collor's list here:
   ...
}
Elad Tabak
  • 2,317
  • 4
  • 23
  • 33