问题
I have data from a ResultSet that contains three fields: DataType, Data, DataValue. I want to build a Java Collection, and next build the JSON encode.
This is the output when I try to print:
System.out.println(resultSet.getString("DATATYPE") + " --> " + resultSet.getString("DATA") + " --> " + resultSet.getString("DATAVALUE"));
Output:
Address --> Test --> JHGJHGJKG
Address --> City--> Some city
Address --> State --> Some state
Address --> Downtown --> Some downtown
Address --> Telephone --> 547455654
Address --> Street --> Some street
Customer Information --> Downtown --> some other downtown
Customer Information --> Job --> Programmer
Customer Information --> Identification card --> ID32443
Customer Information --> ZIP Code --> 74584
Customer Information --> Kind of person --> Regular
Customer Information --> Birthday --> 10 01 1980
Customer Information --> Telephone --> 99832498
Other --> Last visit --> 10 01 1980
I attemped with Guava Google Collections like this:
Map<String, String> data = new HashMap<String,String>();
HashMultimap<String, Map> multiMap = HashMultimap.<String, Map> create();
...
//iterating the resultSet
..
data.put(resultSet.getString("DATA"), resultSet.getString("DATAVALUE"));
multiMap.put(resultSet.getString("DATATYPE"), data);
..
// resultSet ends
The the resulting Collection/Multimap would be:
{
[
Address = {
Test = somevalue,
City = SomeCity,
...
},
Customer Information={
Job = programer,
Identificationcard = ID34234,
...
},
Other{
Lastvisit = 10-02-1990
}
]
}
I've tried, but no successful results.
All the results from ResultSet are dynamically, dynamic type, data and value. I can't use definided classes, for example for an Address data, based on the input data could not be shown.
回答1:
You can have a generic domain object like this:
Dataobject {
dataType;
data;
dataValue;
Set<Dataobject>descendents;
}
That will give you the endless depth of chaining.
while you iterate the resultset, you can decide whether you want to create them at the same level or increasing depth.
after all that is done, use XStream() to marshall it into an xml string.
回答2:
You need to create classes representing your data. You would have Address
, CustomerInformation
etc. - then you may create a wrapper class, say, Customer
that represents everything (Address
, CustomerInformation
).
As you read records from database, you may populate new objects of Address
and CustomerInformation
and populate your Customer
object, and feed it in to a collection.
Then, you may create a utility class that will go through each element in this value object collection and convert it in to appropriate JSAON notation.
来源:https://stackoverflow.com/questions/9741842/how-to-build-this-java-collection-from-a-resultset