xhu_008 2011-12-14 08:50
浏览 812
已采纳

怎样将webservice服务发出的数据转为Json格式的

我刚入职不久,求大神指教。以下是我写的代码,但是编译出错了。比较我急,求大侠帮助

import java.util.HashMap;
import java.util.Map;

//import org.json.*;
import org.json.JSONException;
import org.json.JSONObject;

public class test {

public static void main(String[] args) {
    String json = "{\"name\":\"reiz\"}";
    JSONObject jsonObj = null;

// try {
JSONObject jsonObj = new JSONObject(json);
String name = jsonObj.getString("name");

        jsonObj.put("initial", name.substring(0, 1).toUpperCase());

        String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" };
        jsonObj.put("likes", likes);

// } catch (Exception e) {
// e.printStackTrace();
// }
Map ingredients = new HashMap();
ingredients.put("apples", "3kg");
ingredients.put("sugar", "1kg");
ingredients.put("pastry", "2.4kg");
ingredients.put("bestEaten", "outdoors");
try {
jsonObj.put("ingredients", ingredients);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(jsonObj);

    System.out.println(jsonObj);
    System.out.print(json);

错误在这句话:
JSONObject jsonObj = new JSONObject(json);

还有我写了一个服务 为什么发布不了啊
public void doService(HttpServletRequest request, HttpServletResponse response) throws IOException {

String s1 = request.getParameter("username");

String s2 = request.getParameter("passwd");
// JSONObject jsonObj = new JSONObject(s3);

try {

JSONObject jsonObj1 = new JSONObject(s1);

JSONObject jsonObj2= new JSONObject(s2);
System.out.println(jsonObj1.getString("model"));

System.out.println(jsonObj2.getInt("year"));

response.getWriter().print(jsonObj1.toString());

response.getWriter().print(jsonObj2.toString());
} catch (JSONException e) {
e.printStackTrace();
}
// response.getWriter().print("{ \"name\": \"Violet\", \"occupation\": \"character\" }");
// response.getWriter().print(jsonObj.toString());

}
如果去掉这个服务就可以发布。

  • 写回答

4条回答

  • kinming 2011-12-14 14:12
    关注

    你用的是哪个JSON库?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致