mercredi 22 février 2017

How to build Json from unknown parameters and unknown number of them in java?

I have different commands :

Command1(String name, Integer age) extends BasicCommand
Command2(String address, Info cityInfo)  extends BasicCommandWithException// Info is a class containing 2 fields : city name and city size
Command3(CountryInfo countryInfo, String continent) extends BasicCommandWithCityNameAndException

[BasicCommandWithCityNameAndException extends BasicCommandWithException extends BasicCommand]

I can't add a new abstract class for extension, so I thought of a wrapper that will contain a command and the parameters. I want to be able to convert the passed parameters to a json to I will have something like this:

Wrapper c = new Wrapper(Command1 ("hello", 55))
cityInfo cit = new cityInfo("city", 1000)
Wrapper b = new Wrapper(Command2("myAddress", cit))

String x = c.getJsonFromParams
will print:
{
   "name" : "hello",
   "age" : 55
}

String y = b.getJsonFromParams
will print:
{
    "address" : "myAddress",
    "cityInfo": {
                 "cityName" : "city",
                 "citySize" : 1000
                }  
}

have no idea where to start from. I can't figure out how to pass these parameters as thy can change (the type, the number of them etc) Can you please advise?





Aucun commentaire:

Enregistrer un commentaire