简体   繁体   中英

JSON mapping in Java from string to string array

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.

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:
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM