将基于spring的json字符串转换为Object对象

1.将json的String转换为json对象

1.1导jar包
在maven里的jar包依赖文件

      
        net.sf.json-lib  
        json-lib  
        2.1  
        jdk15  
  

1.2在类里的实现

package com.memorynotfound.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.web.client.RestTemplate;
import com.hanks.entity.Location;
import net.sf.json.JSONObject;
public class Consumer implements MessageListener {

  public static final String WEBSCOKET_REST_SERVICE_URI = "http://localhost:8080/AngularSpringmvcMybatis/stocks/layout";

public void onMessage(Message message) {
    //System.out.println((Object)new String(message.getBody()));
    //获取json对象的实体并将其解析为String
    String json=new String(message.getBody());
    //将解析到的json的字符串转换为JSONObject
    JSONObject jsonObject = JSONObject.fromObject(json);
    //在json对象里将实体的属性字段取出来
    String locationId = jsonObject.getString("locationId");
    String LedStatus = jsonObject.getString("LedStatus");
    String lockStatus = jsonObject.getString("lockStatus");
    //类型的转换-----因为web的数据库类型是int型的
    int locationid= Integer.parseInt(locationId);
    int ledstatus=  Integer.parseInt(LedStatus); 
    int lockstatus= Integer.parseInt(lockStatus);
    //new一个location对象,   
    Location location=new Location();
    location.setLocationid(locationid);
    location.setLedstatus(ledstatus);
    location.setLockstatus(lockstatus);

    RestTemplate restTemplate = new RestTemplate(); 
    String url = WEBSCOKET_REST_SERVICE_URI;
    restTemplate.put(url,(Object)location);
    System.out.println("after rest send.");

    }
}

你可能感兴趣的:(java开发)