I want to create JSON object of selected options. I've already written java code but it creates JSON of all the database values.
The JSON code is:
rs = stmt.executeQuery("SELECT file_id,fid from nonspatial_data where file_id=1");
JSONArray jArray = new JSONArray();
while (rs.next())
{
String FileID_json=rs.getString("file_id");
String fid_json=rs.getString("fid");
JSONObject jobj = new ``JSONObject();
jobj.put("file_id", FileID_json);
jobj.put("fid", fid_json);
jArray.add(jobj);
}
JSONObject features = new JSONObject();
features.put("features", jArray);
I want to create json of selected file_id.
Any assistance is appreciated.
I'm not sure the format you want the json to be in but you should really use a library like jackson (has serializers/mappers that help). The way to use that is: create a domain object representing a json object and pass it through this serializer and you have json.
NOTE: to keep code brief, I don't use best practices of java (eg making string constants, etc). I have also not tested this code but you should get a very good idea of what I'm suggesting.
public class SomeObject{
Map<String,Object> model;
public void setFoo( String foo ) {...}
public String getFoo() {
return model.get( "foo" );
}
// if you have more than one model, consider moving this method to a superclass
public String toJson() {
Map<String, Object> result = new HashMap<String, Object>();
String status;
List<String> errors = new ArrayList<String>();
ObjectMapper mapper = new ObjectMapper();
result.put("status", status);
result.put("errors", errors);
StringWriter sw = new StringWriter();
mapper.writeValue(sw, result);
return sw.toString();
}
}
This helps keep your code object-oriented...and your app logic can then refer to domain objects instead of manipulating basic strings.
我用冬眠做很多时间,然后用flexjson将集合的对象转换成json
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.