A. java 访问一个接口得到接口返回JSON,步骤是怎么做的
java中的接口是一种特殊的类,使用关键字interface创建。接口功能完全实现后,可以打成jar包,提供给其他公司使用。
要返回json格式数据,可以把接口中抽象方法的返回值类型规定为JSONObject或JSONString类型。这样当其他公司调用时,得到的数据就是json数据了。
另外,以jar形式提供的接口,可以通过反编译得到你的源码,如果你不希望开源,就要加密了。
B. web环境下,servlet如何设计java接口接收json,并将处理结果按json格式返回
JSONObject jsonObject = new JSONObject();\x0d\x0aMap map = request.getParameterMap();\x0d\x0aIterator it = map.keySet().iterator();\x0d\x0awhile(it.hasNext()){\x0d\x0aString key = (String)it.next();\x0d\x0aString[] values = (String[])map.get(key);\x0d\x0ajsonObject.accumulate(key, values[0]);\x0d\x0a}\x0d\x0a\x0d\x0aString name = jsonObject.getString("userName"); //返回从前台接受的用户名\x0d\x0aSystem.out.println(name); //输出用户名\x0d\x0a\x0d\x0ajsonObject.clear(); // 清空jsonObjec中的数据\x0d\x0ajsonObject.put("love" , "足球"); //将足球赋给love这个变量名\x0d\x0aout.print(jsonObject); //返回json格式的数据
C. java如何返回json格式
例如:
Student st1 = new Student(1, "dg", 18, new Date());
Student st2 = new Student(2, "dg", 18, new Date());
Student st3 = new Student(3, "dg", 18, new Date());
Student st4 = new Student(4, "dg", 18, new Date());
Student st5 = new Student(5, "dg", 18, new Date());
List li = new ArrayList();
JSONObject JO1 = new JSONObject(st1);
JSONObject JO2 = new JSONObject(st2);
JSONObject JO3 = new JSONObject(st3);
JSONObject JO4 = new JSONObject(st4);
JSONObject JO5 = new JSONObject(st5);
li.add(JO1);
li.add(JO2);
li.add(JO3);
li.add(JO4);
li.add(JO5);
JSONArray Ja = new JSONArray(li);
Map ma = new HashMap();
ma.put("Result", "OK");
ma.put("Records", Ja);
JSONObject js = new JSONObject(ma);
out.print(js);
返回结果:
{"Result":"OK","Records":[{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":1},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":2},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":3},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":4},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":5}]}
D. java如何返回json格式
处理基本的java对象使用JSONObject类,用法大体如下:
public void testMap(){
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", "qiu");
map.put("password", "123");
map.put("address", "china");
User user = new User();
user.setUserName("qiuqiu");
user.setPassword("123456");
user.getTels().add("1234444556677");
user.getTels().add("6893493458585");
map.put("user", user);
JSONObject json = new JSONObject(map);
System.out.println(json.toString());
}