简体   繁体   English

使用Java将JSON作为字符串返回

[英]Return JSON as string with Java

I have always used XML for returning data from my servlets and i have decided to have a go with JSON.Simple. 我一直使用XML从servlet返回数据,因此决定使用JSON.Simple。

I currently have; 我目前有;

    public JSONObject loadDetails() throws IOException {


    JSONArray list = new JSONArray();
    list.add(new Car("car1",3,4,3,2,4,5));
    list.add(new Car("car2",3,4,3,2,4,5));

    StringWriter out = new StringWriter();

    list.writeJSONString(out);

     System.out.println(out.toString());

    return null;
}

I am trying to store some car details, however when i try and print i just get the object names rather than the correct JSON value. 我正在尝试存储一些汽车详细信息,但是当我尝试打印时,我只是获得对象名称而不是正确的JSON值。 My car class implements JSONStreamAware eg; 我的汽车类实现了JSONStreamAware,例如;

 public void writeJSONString (Writer out) throws IOException{
    LinkedHashMap obj = new LinkedHashMap();
    obj.put("carname", carname);
    obj.put("engine", engine);

    JSONValue.writeJSONString(obj, out);
}

Have i missed something here? 我在这里错过了什么吗?

I am sorry, I know that this is not what you are explicitly asking for but I will definitely recommend using Gson for json parsing. 对不起,我知道这不是您明确要求的,但是我绝对会建议使用Gson进行json解析。 You jsut specify several annotations and everything is magically serialized / deserialized. 您只需指定几个批注,然后所有内容都会神奇地序列化/反序列化。 Read about gson here . 在这里阅读有关gson的信息 Again sorry that this is not exact answer of the question, but still I hope it will help you get started in json. 再次抱歉,这不是问题的确切答案,但我仍然希望它能帮助您开始使用json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM