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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料