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

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services