我想从数据库制作JSON对象,但是有一个复杂的结构。我不清楚如何在下面的Json字符串中制作诸如“值”之类的复杂结构。帮助任何人,谢谢。这是我要制作的Json字符串:
[{"type":"person1","id":null,"values":[[[32.3619,50.9291],[32.3604,50.9644],[32.3446,50.9395]]]}]
我尝试过的代码。
Session sess1 = sf.openSession();
Query q = sess1.createQuery("from person");
List l = q.list();
Iterator itr = l.iterator();
JSONArray jArray = new JSONArray();
JSONObject jObj = new JSONObject();
String id = null, lat, lng;
while (itr.hasNext()) {
Person pobj = (Person) itr.next();
id = pobj.getId().toString();
lat = pobj.getLatitude();
lng = pobj.getLongitude();
}
jObj.put("type", "Person1");
jObj.put("id", id);
JSONArray jrray = new JSONArray();
jArray.put(jObj);
JSONObject jObjDevice = new JSONObject();
jObjDevice.put("", jArray);
System.out.println("json object created" + jObjDevice.toString());
使用杰克逊...
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class MapToJsonExample {
private static final String pathToJsonResult = "example.json";
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> mapObject = new HashMap<String, Object>();
mapObject.put("type", "person1");
mapObject.put("id", null);
List<Object> myList = new ArrayList<>();
List<Double> point1 = Arrays.asList( 32.3619,50.9291 );
List<Double> point2 = Arrays.asList( 32.3446,50.9395 );
List<List<Double>> innerList = new ArrayList<>();
List<List<List<Double>>> outerList = new ArrayList<>();
innerList.add( point1 );
innerList.add( point2 );
outerList.add( innerList );
mapObject.put( "values", outerList );
try {
objectMapper.writeValue(new File(pathToJsonResult), mapObject);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这里,使用Windows和Java7对其进行
编译。
javac -cp .;jackson-all-1.9.11.jar MapToJsonExample.java
运行...
java -cp .;jackson-all-1.9.11.jar MapToJsonExample
瞧!
type example.json
{"values":[[[32.3619,50.9291],[32.3446,50.9395]]],"id":null,"type":"person1"}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句