Converting the Database details to JSON object - java

I have a table with has the columns namely
recordID, recordName , titleFeild, titleIDMap, titleId, titleStartDate, titleEndDate, languageId
Now I have convert the data from above columns to the JSON object data which looks like below
{
"recordId" :10,
"recordName" : "RECORDS",
"records" : [ {
"titleField" : 1,
"titleIDMap" : null,
"titleId" : 500,
"titleStartDate" : "2013-12-22T00:00:00.000+0000",
"titleEndDate" : "2013-12-03T00:00:00.000+0000",
"languageId" : 20
}]
}
Please note that records is an array of columns ( titleFeild,titleIDMap,titleId,titleStartDate,titleEndDate,languageId)
The code so far I have developed is
List<Object[]> objList = dao.getStatus();
Integer result = null;
JSONObject jsonData = new JSONObject();
JSONArray jsonDataArray = new JSONArray();
if(objList!=null && objList.size()>10000)
{
for (Object[] nameObj : objList) {
jsonData.put("", nameObj.get(arg0) );
}
}
How do I construct the JSON Object from the columns data ?

You can easily achieve this with google-gson library. In simple terms you would have to create a couple of Pojos (with reference to another containin a list of references).
Consider RecordID and RecordName as Meta Data.
Create a pojo representing this information:
public class DbMetaPojo {
private int recordID;
private String recordName;
private List<Record> records;
public List<Record> getRecords() {
return records;
}
public void setRecords(List<Record> records) {
this.records = records;
}
public String getRecordName() {
return recordName;
}
public void setRecordName(String recordName) {
this.recordName = recordName;
}
public int getRecordID() {
return recordID;
}
public void setRecordID(int recordID) {
this.recordID = recordID;
}
}
Create another pojo with the actual Record fields:
public class Record {
public int getTitleFeild() {
return titleFeild;
}
public void setTitleFeild(int i) {
this.titleFeild = i;
}
public String getTitleIDMap() {
return titleIDMap;
}
public void setTitleIDMap(String titleIDMap) {
this.titleIDMap = titleIDMap;
}
public int getTitleId() {
return titleId;
}
public void setTitleId(int titleId) {
this.titleId = titleId;
}
public String getTitleStartDate() {
return titleStartDate;
}
public void setTitleStartDate(String titleStartDate) {
this.titleStartDate = titleStartDate;
}
public String getTitleEndDate() {
return titleEndDate;
}
public void setTitleEndDate(String titleEndDate) {
this.titleEndDate = titleEndDate;
}
public int getLanguageId() {
return languageId;
}
public void setLanguageId(int languageId) {
this.languageId = languageId;
}
private int titleFeild;
private String titleIDMap;
private int titleId;
private String titleStartDate;
private String titleEndDate;
private int languageId;
}
Now just a method to populate your POJOs with the relevant data (replace the hardcoding logic with your data retrieve):
public static void main(String... main) {
DbMetaPojo obj = new DbMetaPojo();
obj.setRecordID(10);
obj.setRecordName("RECORDS");
Record record = new Record();
record.setLanguageId(20);
record.setTitleEndDate("2013-12-22T00:00:00.000+0000");
record.setTitleFeild(1);
record.setTitleId(500);
record.setTitleIDMap("SOME NULL");
record.setTitleStartDate("2013-12-22T00:00:00.000+0000");
List<Record> list = new ArrayList<Record>();
list.add(record);
obj.setRecords(list);
Gson gson = new Gson();
String json = gson.toJson(obj);
System.out.println(json);
}
Output is your formed JSON:
{
"recordID": 10,
"recordName": "RECORDS",
"records": [
{
"titleFeild": 1,
"titleIDMap": "SOME NULL",
"titleId": 500,
"titleStartDate": "2013-12-22T00:00:00.000+0000",
"titleEndDate": "2013-12-22T00:00:00.000+0000",
"languageId": 20
}
]
}
EDIT:
To align to your code, you might want to do something like:
List<Object> objList = dao.getStatus();
List<DbMetaPojo> metaList = new ArrayList<DbMetaPojo> ();
if (objList != null && objList.size() > 10000) {
for (Object nameObj : objList) {
DbMetaPojo meta = new DbMetaPojo();
meta.setRecordID(nameObj[0]);
meta.setRecordName(nameObj[0]);
...
...
...
metaList.add(meta);
}
}

First of all what you have to do is retrieve the data from the columns of the table using your DAO and calling a Function from DAOIMPL which in turn will return the list of data(POJO probably).
Create a map like this which will contain your key value pair for example recordid and value,
recordname and value
Map<String,Object> objMap = new HashMap<String,Object>();
objMap.put("recordId", Record.getId());
objMap.put("recordName",Record.getName());
// Now here is the deal create another hashmap here whose key will be records "the key for your second array"
//Put the values in this second hashmap as instructed above and put it as a key value pair.
........
.......
.......
JSONObject JsonObject = JSONObject.fromObject(objMap);//This will create JSON object out of your hashmap.
objJSONList.add(JsonObject);
}
StringBuffer jsonBuffer = new StringBuffer();
jsonBuffer.append("{\"data\": {");
jsonBuffer.append(objJSONList.tostring());
jsonBuffer.append("}");
//jsonBuffer.append(",\"total\":"+ objJSONList.size());// TOTAL Optional
//jsonBuffer.append(",\"success\":true}");//SUCCESS message if using in callback Optional

Create an object which has your attribues. (recordID, recordName , titleFeild, titleIDMap, titleId, titleStartDate, titleEndDate, languageId)
Get data from dao and convert it to json. It will looks like what you want.
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);

I think your dao.getStatus() should return a List with Map keys and values. Your key would be column name and value would be content.
List<Map<String,Object>> objList = dao.getStatus();
if(objList!=null && objList.size()>10000){
for(Map<String,Object> row : objList) {
Iterator<String> keyList = row.keySet().iterator();
while(keyList.hasNext()){
String key = keyList.next();
jsonData.put(key, row.get(key));
}
}
}
For the records array you need to build it while iterating table columns.
Combining above code with building records array would be something like this..
String[] group = {"titleField","titleIDMap","titleId","titleStartDate","titleEndDate","languageId"};
List<String> recordGroup = Arrays.asList(group);
Map<Object, JSONArray> records = new HashMap<Object,JSONArray>();
List<Map<String,Object>> objList = dao.getStatus();
JSONObject jsonData = new JSONObject();
if(objList!=null && objList.size()>10000){
for(Map<String,Object> row : objList) {
int columnCount = 0;
Iterator<String> keyList = row.keySet().iterator();
while(keyList.hasNext()){
String key = keyList.next();
if(recordGroup.contains(key)){
Object recordId = row.get("recordId");
JSONArray recordArray = new JSONArray();
if(records.containsKey(recordId)){
recordArray = records.get(recordId);
JSONObject jsonObj = null;
if(columnCount >= recordGroup.size()){
jsonObj = new JSONObject();
recordarray.add(jsonObj);
columnCount = 0;
}
else {
jsonObj = (JSONObject) recordArray.get(recordArray.size()-1);
}
jsonObj.put(key, row.get(key));
columnCount++;
}
else {
JSONObject jsonObj = new JSONObject();
jsonObj.put(key, row.get(key));
recordArray.add(jsonObj);
records.put(recordId, recordArray);
}
jsonData.put("records", records.get(recordId));
}
else {
jsonData.put(key, row.get(key));
}
}
}
}

Related

Gson- Parsing a JSON array of JSON objects to ArrayList<org.json.JSONObject>

I have a JSON string like this:
{
"r": [
{
"pic": "1.jpg",
"name": "Name1"
},
{
"pic": "2.jpg",
"name": "Name2"
},
{
"pic": "3.jpg",
"name": "Name3"
}
]
}
I want to parse to this POJO model:
public class Catalog {
#SerializedName("r")
#Expose
private List<JSONObject> r = new ArrayList<JSONObject>();
public List<JSONObject> getR() {
return r;
}
public void setR(List<JSONObject> r) {
this.r = r;
}
}
I am parsing this way:
Catalog cat = new Gson().fromJson(jsonString,Catalog.class);
But finally am getting this json
{
"r": [
{
"nameValuePairs": {}
},
{
"nameValuePairs": {}
},
{
"nameValuePairs": {}
}
]
}
Please note that I don't want to use com.google.gson.JsonObject.
I want to use org.json.JSONObject. How to achieve this because almost all of my code uses it?
As it was already mentioned in other answer and comments, you probably might not really want to use org.json.JSONObject for several reasons. But if it's a must for you, you just have to create your org.json.JSONObject-aware Gson instance.
final class JSONObjectJsonDeserializer
implements JsonDeserializer<JSONObject> {
// The implementation is fully thread-safe and can be instantiated once
private static final JsonDeserializer<JSONObject> jsonObjectJsonDeserializer = new JSONObjectJsonDeserializer();
// Type tokens are immutable values and therefore can be considered constants (and final) and thread-safe as well
private static final TypeToken<Map<String, Object>> mapStringToObjectTypeToken = new TypeToken<Map<String, Object>>() {
};
private JSONObjectJsonDeserializer() {
}
static JsonDeserializer<JSONObject> getJsonObjectJsonDeserializer() {
return jsonObjectJsonDeserializer;
}
#Override
public JSONObject deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) {
// Convert the input jsonElement as if it were a Map<String, Object> (a generic representation for JSON objectS)
final Map<String, Object> map = context.deserialize(jsonElement, mapStringToObjectTypeToken.getType());
// And forward the map to the JSONObject constructor - it seems to accept it nice
return new JSONObject(map);
}
}
Gson is designed thread-safe and does not need to be instantiated every time serialization or deserialization is necessary:
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(JSONObject.class, getJsonObjectJsonDeserializer())
.create();
And finally:
final Catalog catalog = gson.fromJson(jsonString, Catalog.class);
out.println(catalog.getR());
with the following result:
[{"name":"Name1","pic":"1.jpg"}, {"name":"Name2","pic":"2.jpg"}, {"name":"Name3","pic":"3.jpg"}]
Anyway, I would suggest you to redesign your mappings model.
I think you don't need JSONObject.
Try this
// is wrapped class for serialized json.
public class JsonExample
{
List<Catalog> r;
}
public class Catalog {
private String pic;
private String name;
public String getPic() {
return pic;
}
public String getName() {
return name;
}
}
JsonExample example = new Gson().fromJson(json, JsonExample.class);
Additional - using JSONObject
JSONObject obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("r");
List<Catalog> cataList = new ArrayList<>();
for(int i = 0 ; i < arr.length() ; ++i)
{
cataList.add(new Catalog(arr.getJSONObject(i)));
}
public class Catalog {
private String pic;
private String name;
public Catalog(JSONObject obj) throws JSONException
{
pic = obj.getString("pic");
name = obj.getString("name");
}
public String getPic() {
return pic;
}
public String getName() {
return name;
}
}
I think in your case, usage of gson library is not required at all.
Only org.json can solve the entire problem.
E.g.:
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("r");
List<JSONObject> jsonList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
Catalog catalog = new Catalog();
catalog.setR(jsonList);

Json text to RecyclerView in Android

I need help with my RecyclerView. I have a atring array from my SQL Database which looks like this:
{"success":true,"0":{"order_number":"078","typ_first":"E3rft","typ_last":"Split","order_date_time":"2016-10-11 19:20:03"},"1":{"order_number":"166","typ_first":"E483f","typ_last":"Split_test","order_date_time":"2016-10-12 18:39:30"}}
In my RecyclerView I have the following fields:
order_number
typ_all (type first and last)
date(only a date without time)
This is how I get my string array:
String plansData = plansPreferenceData.getString("plansPreferenceData", "");
This is how I set the data to my RecyclerView:
// Set plan data
Plans plan = new Plans("123", "E3rft Split", "11.10.2016");
// Add Object to list
planList.add(plan);
// Notify data changes
pAdapter.notifyDataSetChanged();
My Plans class:
public class Plans {
private String planTitle, planType, planDate;
public Plans(String planTitle, String planType, String planDate) {
this.planTitle = planTitle;
this.planType = planType;
this.planDate = planDate;
}
public void setPlanTitle(String planTitle) {
this.planTitle = planTitle;
}
public String getPlanTitle() {
return planTitle;
}
public void setPlanType(String planType) {
this.planType = planType;
}
public String getPlanType() {
return planType;
}
public void setPlanDate(String planDate) {
this.planDate = planDate;
}
public String getPlanDate() {
return planDate;
}
}
My onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_training, container, false);
preparePlansData();
return view;
}
My preparePlansData():
private void preparePlansData() {
// Set plan data
Plans plan = new Plans("123", "fkfjfjeje", "21.04.1977");
// Add Object to list
planList.add(plan);
plan = new Plans("test", "tttt", "22.01.2017");
planList.add(plan);
// Notify data changes
pAdapter.notifyDataSetChanged();
}
My question is how can I get the information out of the string array into my adapter? I also need to format the date before adding. Thanks for your help!
read about Gson here:
http://guides.codepath.com/android/leveraging-the-gson-library
After that you will be able to write code like that:
Type type = new TypeToken<Map<Integer, Plans>>(){}.getType();
Map<Integer, Plans> myMap = gson.fromJson("your json from db", type);
and use this map.values() in your adapter
your Plans class should look like this:
class Plans {
String order_number;
String typ_first;
String typ_last;
String order_date_time;
}
If you want another field names you have to use #SerializedName annotation
Finally, you should write something like that, (I do not know if syntax is 100% do not have IDE open now) :
private void preparePlansData() {
String plansData = plansPreferenceData.getString("plansPreferenceData", "");
Type type = new TypeToken<Map<Integer, Plans>>(){}.getType();
Map<Integer, Plans> myMap = gson.fromJson(plansData, type);
planList.addAll(myMap.values());
// Notify data changes
pAdapter.notifyDataSetChanged();
}
and modify your model class:
public class Plans {
#SerializedName("order_number")
String planTitle;
#SerializedName("typ_last")
String planType;
#SerializedName("order_date_time")
String planDate;
....
I hope it will help you.
Check this code (you can remove #Test annotation):
class Plans {
String typ_firstString;
String typ_last;
String order_date_time;
public Plans(String typ_firstString, String typ_last, String order_date_time) {
this.typ_firstString = typ_firstString;
this.typ_last = typ_last;
this.order_date_time = order_date_time;
}
}
class PlansResponse {
boolean status;
List<Plans> plans;
}
#Test
public void testPlacesResponseDeserializer() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(PlansResponse.class, new PlansResponseDeserializer())
.create();
String jsonString = "{\"success\":true,\"0\":{\"order_number\":\"078\",\"typ_first\":\"E3rft\",\"typ_last\":\"Split\",\"order_date_time\":\"2016-10-11 19:20:03\"},\"1\":{\"order_number\":\"166\",\"typ_first\":\"E483f\",\"typ_last\":\"Split_test\",\"order_date_time\":\"2016-10-12 18:39:30\"}}";
PlansResponse plansResponse = gson.fromJson(jsonString, PlansResponse.class);
assert plansResponse.status == true;
assert plansResponse.plans.size() == 2;
}
class PlansResponseDeserializer implements JsonDeserializer<PlansResponse> {
private String getElementAsString(JsonObject jsonObject, String key) {
JsonElement element = jsonObject.get(key);
return element.getAsString();
}
#Override
public PlansResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
PlansResponse plansResponse = new PlansResponse();
List<Plans> plansList = new ArrayList<>();
Gson gson = new Gson();
Type type = new TypeToken<Map<String, JsonObject>>(){}.getType();
Map<String, JsonElement> map = gson.fromJson(json, type);
for(Map.Entry<String, JsonElement> entry : map.entrySet()) {
String key = entry.getKey();
if("success".equals(key)) {
JsonPrimitive jsonPrimitive = (JsonPrimitive) entry.getValue();
plansResponse.status = jsonPrimitive.getAsBoolean();
continue;
}
JsonObject jsonObject = (JsonObject)entry.getValue();
String typ_firstString = getElementAsString(jsonObject, "typ_first");
String typ_last = getElementAsString(jsonObject, "typ_last");
String order_date_time = getElementAsString(jsonObject, "order_date_time");
plansList.add(new Plans(typ_firstString, typ_last, order_date_time));
}
plansResponse.plans = plansList;
return plansResponse;
}
}

Convert object containing repeated fields to JSON

I have two table country and city in mysql dababase and i make a query to return records like that as List<myDTO> :
1,france,1,paris
1,france,2,marseille
1,france,3,lion
....
MyDTO
public class MyDTO {
public Integer idLvl1;
public String nameLvl1;
public Integer idLvl2;
public String nameLvl2;
public MyDTO(Integer idLvl1, String nameLvl1, Integer idLvl2, String nameLvl2) {
this.idNiv1 = idLvl1;
this.nomNiv1 = nameLvl1;
this.idNiv2 = idLvl2;
this.nomNiv2 = nameLvl2;
}
How can i convert it to json object to avoid the repeating country :
[
{"idNiv1" :1,"nameLvl1":"France","cities":[{"idNiv2":1,"nameLvl2":"paris"}]}
{"idNiv1" :1,"nameLvl1":"France","cities":[{"idNiv2":2,"nameLvl2":"marseille"}]}
{"idNiv1" :1,"nameLvl1":"France","cities":[{"idNiv2":3,"nameLvl2":"lion"}]}
....
]
to
[
{
"idNiv1" :1,
"nameLvl1":"France",
"cities":[
{ "idNiv2":1,"nameLvl2":"paris" } ,
{ "idNiv2":2,"nameLvl2":"marseille" } ,
{ "idNiv2":3,"nameLvl2":"lion" }
]
}
....
]
You can use Google's Gson in this case :
public String getJSONFromResultSet(ResultSet rs, String key) {
Map json = new HashMap();
List list = new ArrayList();
if (rs != null) {
try {
ResultSetMetaData mData = rs.getMetaData();
while (rs.next()) {
Map<String, Object> columns = new HashMap<String, Object>();
for (int columnIndex = 1; columnIndex <= mData.getColumnCount(); columnIndex++) {
if (rs.getString(mData.getColumnName(columnIndex)) != null) {
columns.put(mData.getColumnLabel(columnIndex),
rs.getString(mData.getColumnName(columnIndex)));
} else {
columns.put(mData.getColumnLabel(columnIndex), "");
}
}
list.add(columns);
}
} catch (SQLException e) {
e.printStackTrace();
}
json.put(key, list);
}
return new Gson().toJson(json);
}
Update:
You can call getJSONFromResultSet method like below :
Connection con = DBConnectionClass.myConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM Customer");
//as an example consider a table named Customer in your DB.
ResultSet rs = ps.executeQuery();
System.out.println(getJSONFromResultSet(rs, "customer"));
Create additional classes for country and city. Transform the flat structure to nested structure of country and cities as shown below:
public class Country {
Integer idLvl1;
String nameLvl1;
public Country(Integer idLvl1, String nameLvl1) {
}
List<City> cities;
}
public class City {
Integer idLvl2;
String nameLvl2;
public City(Integer idLvl2, String nameLvl2) {
}
}
public class MyDTOConverter {
public static Collection<Country> covert(List<MyDTO> dtos){
Map<Integer, Country> countries = new LinkedHashMap<Integer, Country>();
for (MyDTO myDTO : dtos) {
//First adding the country if it doesn't exist
if (!countries.containsKey(myDTO.idLvl1)){
countries.put(myDTO.idLvl1, new Country(myDTO.idLvl1, myDTO.nameLvl1));
}
//Adding city in the existing country.
countries.get(myDTO.idLvl1).cities.add(new City(myDTO.idLvl2, myDTO.nameLvl2));
}
return countries.values();
}
}
The final Collection of Country will result is the desired JSON.
You can write Wrapper DTO on top of Your MyDTO and then use any available json libraries like Google's Gson to convert to required JSON format.
Regards,
Sakumar

How to extract array values within nested JSON data

I have JSON data in the following format:
{
"data": {
"id": 14810798216415,
"name": "crescentbahuman.com",
"is_organization": true,
"email_domains": [
"crescentbahuman.com"
]
}
}
I want to get the string in the "email_domains" field. I wrote the following code as my attempt:
JSONObject dataObject2= (JSONObject)jsonObject2.get("data");
long id = (long) dataObject2.get("id");
System.out.println("worksapce id is: " + id);
String name = (String) dataObject2.get("name");
System.out.println("The worksapce name is: " + name);
boolean is_organization = (boolean) dataObject2.get("is_organization");
System.out.println("The workspace is organization: " + is_organization);
JSONArray email_domains = (JSONArray) jsonObject2.get("email_domains");
Iterator<String> iterator = email_domains.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
In this code to get "email_domains" only, a JSON Array object is created that get data from the JSON object and then its iterator is used to get values from within the array. However, it throws a NullPointerException on this line:
Iterator<String> iterator = email_domains.iterator();
I am stuck due to this problem. Can anyone kindly suggest a solution?
If you are using the JSON library from http://www.json.org/java/, then you should not be using JSONObject.get() so frequently. The library has other methods to get specific types, such as getLong(), getJSONArray(), and so forth. For your case with the "email_domains" field, you should try:
JSONArray array = dataObject2.getJSONArray("email_domains");
String value = array.getString(0);
org.json.JSONArray email_domains = (org.json.JSONArray) json.get("email_domains");
int length = email_domains.length();
for(int i = length-1; i > 0; i--) {
org.json.JSONObject jsonData = (org.json.JSONObject) email_domains.get(i);
System.out.println(jsonData);
}
My solution? I hate to be someone to offer a solution in another library... but look into google collections and the Gson helper. It can turn your Json into a map for you, and then back to json again when you are done.
Map map = gson.fromJson(jsonText, Map.class);
JsonArray's can then be cast into List's
try this to fetch "email_domains"
JSONArray email_domains = ((JSONArray) jsonObject).get("email_domains");
or
JSONObject obj = new JSONObject(jsonObject.Tostring());
JSONArray email_domains = obj.optJSONArray("email_domains");
"email_address" is JSONArray so we need to fetch this like
JSONArray email_domains = (JSONArray) dataObject2.getJSONArray("email_domains");
email_domains.get(0); // this will return crescentbahuman.com
Use this implementation
import java.lang.reflect.Field;
import java.util.List;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonConvertor {
private static GsonBuilder gsonBuilder;
private static Gson gson;
private JsonConvertor() {
}
public static Object fromJson(String json, Class clz)
{
gson=new Gson();
return gson.fromJson(json,clz);
}
public static String toJson(Object obj) {
gsonBuilder = new GsonBuilder();
gsonBuilder = gsonBuilder
.addSerializationExclusionStrategy(new CustomIclusionStrategy(
obj.getClass()));
gson = gsonBuilder.create();
String json = gson.toJson(obj);
return json;
}
}
class CustomIclusionStrategy implements ExclusionStrategy {
private Class classToIclude;
private Field[] declaredFields;
private List<FieldAttributes> fields;
public CustomIclusionStrategy(List<FieldAttributes> fields) {
this.fields = fields;
}
public CustomIclusionStrategy(Class classToIclude) {
this.classToIclude = classToIclude;
this.declaredFields=classToIclude.getDeclaredFields();
}
// called only if shouldSkipClass returns false
#Override
public boolean shouldSkipField(FieldAttributes f) {
try {
classToIclude.getSuperclass().getDeclaredField(f.getName());
System.out.println(f.getName());
return true;
} catch (Exception e) {
}
return false;
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
// if returns false shouldSkipField will be called, otherwise
//shouldSkipField will not be called
return false;
}
}
public class Org {
private Data data;
public Org(Data data) {
super();
this.data = data;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String toJson()
{
return JsonConvertor.toJson(this);
}
public static void main(String[] args) {
String json="{\"data\": {\"id\":\"1\",\"name\":\"org1\",\"is_organization\":true,\"email_domains\": [\"email1\",\"email2\",\"email3\",\"email4\"]}}";
Org o=(Org) JsonConvertor.fromJson(json, Org.class);
System.out.println(o.getData().getEmail_domains());
}
}

How to populate a GWT DataGrid?

I've created a DataGrid so:
DataGrid<String> grid = new DataGrid<String>();
grid.setPageSize(4);
TextColumn<String> date = new TextColumn<String>() {
public String getValue(String object) {
return object;
}
};
grid.addColumn(date, "Date");
TextColumn<String> time = new TextColumn<String>() {
public String getValue(String object) {
return object;
}
};
grid.addColumn(time, "Time");
TextColumn<String> number = new TextColumn<String>() {
public String getValue(String object) {
return object;
}
};
grid.addColumn(number, "Number");
Now I'd like to populate it but I don't understood how to do it because I have these String[] and they must be splitted also:
textString[1]="01/01/2014;10:00;300";
textString[2]="02/02/2014;11:00;400"; ...
Thanks in advance.
UPDATE
#Sturmination I followed your hint but there is another problem for this code(assuming that splitting is done):
..
protected static List<Example> EXAMPLES = null;
..
public void method() {
...
EXAMPLES = Arrays.asList(new Example("01/01/2014", "10:00", "300"));
grid.setRowCount(EXAMPLES.size(), true);
grid.setRowData(0, EXAMPLES);
..
}
It returns this error:
The method setRowData(int, List<? extends String>) in the type AbstractHasData<String> is not applicable for the arguments (int, List<Example>)
And it suggests : Change type of EXAMPLES to List<? extends String> but it doesn't work anyway.
Have you tried this:
DataGrid<String> grid = new DataGrid<String>();
grid.setPageSize(4);
TextColumn<String> date = new TextColumn<String>() {
public String getValue(String object) {
return object.split(';')[0];
}
};
grid.addColumn(date, "Date");
TextColumn<String> time = new TextColumn<String>() {
public String getValue(String object) {
return object.split(';')[1];
}
};
grid.addColumn(time, "Time");
TextColumn<String> number = new TextColumn<String>() {
public String getValue(String object) {
return object.split(';')[2];
}
};
grid.addColumn(number, "Number");
A nicer approach would be to create a new Java Bean for your rows and convert your String[] items to a List<Row> of the new row objects
You can use String[] in your code:
DataGrid<String> grid = new DataGrid<String>();
TextColumn<String[]> date = new TextColumn<String[]>() {
public String getValue(String[] object) {
return object[0];
}
};
Split your strings when you add them:
private ListDataProvider<String[]> dataProvider = new ListDataProvider<String[]>();
private List<String[]> displayItems = dataProvider.getList();
...
for (String textString : textStrings) {
displayItems.add(textString.split(";");
}
I would do it like this, if size of you data is not huge.
Create a class
Class YourClass{
private String date, time, number;
public YourClass(String date, String time, String nuber){
this.date=date;
this.time=time;
this.number=number;
}
//getters and setters here
}
Create a method to conver you values
private List<YourObject> convert(String[] values){
List<YourClass> data= new ArrayList<YourClass>();
String date, time, number;
for(i=0; values.size(); i++){
values[i] //split the string and asign values to date, time and number
dataList.add(new YourClass(date, time, number));
}
return dataList;
}
Add you values to DataGrid
ListDataProvider<YourClass> provider= new ListDataProvider<YourClass>();
List<YourClass> dataList = new ArrayList<YourClass>();
dataList.addAll(convert(textString[]));
provider.addDataDisplay(grid);
provider.setList(dataList);
Then in your Columns just:
return object.getDate();
return object.getTime();
return object.getNumber();

Categories

Resources