我用的工具是MyEclipse10.0,jar包都是开发工具内置的,我做的webServise都是返回xml数据的,求问如何能返回Json数据,客户端又该如何接受这些数据,求详细回答!!!谢谢大家啦!!!
json myeclipse java webservice
把数据转一下就成了json格式的了。javaBean转成json
public class JavaBeanToJson {
public static void main(String[] args) {
ArrayList<Student> list=new ArrayList<Student>();
Student s1=new Student();
s1.setName("leilei");
s1.setAge(23);
Student s2=new Student();
s2.setName("leilei02");
s2.setAge(23);
list.add(s1);
list.add(s2);
StringWriter str=new StringWriter();
ObjectMapper objectMapper=new ObjectMapper();
try {
objectMapper.writeValue(str, list);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(str);
}
}
json返回javaBean
java
public class JsonToJavaBean {
public static void main(String[] args) {
String str="{\"student\":[{\"name\":\"leilei\",\"age\":23,\"gender\":true},{\"name\":\"leilei02\",\"age\":23,\"gender\":false}]}";
Student stu = null;
List<Student> list = null;
try {
ObjectMapper objectMapper=new ObjectMapper();
StudentList studentList=objectMapper.readValue(str, StudentList.class);
list=studentList.getStudent();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(Student s:list){
System.out.println(s.getName()+" "+s.getAge()+" "+s.isGender());
}
}
}
PrintWriter out = null;
System.out.println("\n正在使用json格式将结果传回客户端:"+uMap.get(responseMan));
String jsonText = "[{\"result\":\"添加工作计划成功!\",\"id\":\""+planItem.getFiwpitemId()+
"\",\"planDate\":\""+planDate+"\"," +
"\"content\":\""+content+"\",\"responseMan\":\""+uMap.get(responseMan)+"\"}]";
// jsonText = "[{\"result\":\"添加工作计划成功!\"}]";
try {
out = this.getResponse().getWriter();
JSONArray jsonArray = JSONArray.fromObject(jsonText);
// out.print("{'result':'添加工作计划成功!','id':'"+planItem.getFiwpitemId()+"','planDate':'"+
// new SimpleDateFormat("yyyy-MM-dd").format(planItem.getFdplanDate())+"'," +
// "'content':'"+content+"','responseMan':'"+user.getFcname()+"'}");
out.print(jsonArray);
// out.print(arr.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
out.flush();
out.close();
}
客户端
$.ajax({
type:'post',//可选get
url:'',//这里是接收数据的PHP程序
data:{"planDate":datePlan,"content":content},//传给的数据,多个参数用&连接
dataType:'json',//服务器返回的数据类型 可选XML ,Json jsonp script html text等
success:function(result){
result[0].planDate;
result[0].id;
result[0].content;
result[0].responseMan