为了账号安全,请及时绑定邮箱和手机立即绑定

关于Spring中JSON和对象的转化

关于Spring中JSON和对象的转化

30秒到达战场 2019-07-08 04:04:57
有一个项目是这样:从百度天气API接口获取json字符串,输出到jsp页面。要求用Spring框架开发。我的思路是设计一个dao从百度中获取json,service层调用这个方法。然后在controller中将json转化为weather对象注入jsp,jsp中使用${weather.xxx}的方式输出天气信息。请实现过程。主要是怎么将dao中的json转化为weather返回//controller类似这样:public String getWeather(String city, ModelMap model){Weather weather;//转化过程//...............//..............String json = xxxxx.getJson(); model.addAttribute("weather", weather);return "weather.jsp";}我的意思不是要解析json,而是使用spring来实现。我知道有@RequesBody等等,但是不会用,好像并不能实现我的要求
查看完整描述

3 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

Form formPreview = new Form();
public Leaf(string name) : base(name) { }
public override void Add(Component c)
{
Console.WriteLine("Cannot add to a leaf");
}
public override void Remove(Component c)
{
Console.WriteLine("Cannot remove to a leaf");
}
public override void Display(int depth)
{
Console.WriteLine(new string('-',depth)+name);
}
}

查看完整回答
反对 回复 2019-07-09
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

这个很简单可以使用spring mvc自带的jackson

1、web工程lib中加入jackson所需jar包:jackson-core-asl-1.9.9.jar、jackson-mapper-asl-1.9.9.jar

2、在applicationContext.xml中加入jackson的配置

1

2

3

4

<!-- json转换器 -->

<bean id="jsonConverter"

 class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  <property name="supportedMediaTypes" value="application/json" />

</bean>

3、在你的action中直接使用注解的方式"@ResponseBody"自动将返回值转化成json格式

1

2

3

4

5

6

7

8

9

@Controller

@RequestMapping("task")

public class TaskControl { 

     @RequestMapping("getUserById") 

     @ResponseBody

     public List getUserById(Integer id) {

         return this.taskService.getUserById(id);

     } 

}

4、jsp页面的js写法跟普通ajax格式一样

1

2

3

4

5

functon getUserById(id){

    $.getJSON("task/getUserById",{id:id},function(data){

   

    });  

}



查看完整回答
反对 回复 2019-07-09
  • 3 回答
  • 0 关注
  • 1379 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信