【问题标题】:Parsing json object in java code在java代码中解析json对象
【发布时间】:2015-01-15 19:33:13
【问题描述】:

我被代码困住了,实际上我使用的是 spring MVC 4。我有一个条件,我需要在控制器端传递 json 对象并对其进行迭代。我的 Json 对象如下所示

{"comptocome":[
    {"1":"Key Parameters","2":"Cellular Limited","3":"limited","4":"Cellular Limited"},
    {"1":"- Long term","2":"Reaffirmed","3":"football","4":"golf"}
    ]
}

关于上面我已经将它传递给控制器​​并根据行数进行迭代,例如从上面两次循环,并且还根据键获取数据任何人都可以帮助我在 import org 的帮助下解决这个问题.json.simple.JSONObject 包。

提前致谢。

【问题讨论】:

标签: java json spring-mvc


【解决方案1】:

您可以使用 com.google.gson:

@RequestMapping(value = "/request", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseClass addDeparturePoint(@RequestBody String request) {
    Gson gson = new Gson();
    RequestClass request = gson.fromJson(request, RequestClass.class);
    ResponseClass response = buildResponce(request);
    return response;

}

【讨论】:

    【解决方案2】:

    使用 Jackson JSON 解析

    例如:

    {
    "foo" : ["1","2","3","4"],
    "bar" : "xxxx",
    "baz" : "yyyy"
    }
    

    可以映射到这个类:

    public class Fizzle{
        private List<String> foo;
        private boolean bar;
        private int baz;
        // getters and setters omitted
    }
    

    现在,如果您有这样的 Controller 方法:

    @RequestMapping("somepath")
    @ResponseBody
    public Fozzle doSomeThing(@RequestBody Fizzle input){
        return new Fozzle(input);
    }
    

    【讨论】:

    • 感谢您的回复,我认为没有我们可以实现的 bean 类真的是强迫症吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    相关资源
    最近更新 更多