如何在Spring AMQP中解析JSON对象?

有一个远程RabbitMQ服务器,它只允许我发送和接收消息.这意味着我无法创造任何东西.我发送了一个请求,并以JSON格式得到答案.

在我的应用程序中,我有一个简单的Receiver类:

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

@RabbitListener(queues = "QueueName")
    public void receive(String in) {
        System.out.println(" [x] Received '" + in + "'");
    }
}

我希望收到一个JSON对象.而不是这个我得到一堆数字:

 [x] Received '123,34,97,99,116,105,111,110,34,58,34,103,101,116,73,110,102,111,34,44,34,114,101,115,117,108,116,34,58,34,78,111,116,82,101,103,105,115,116,101,114,101,100,34,44,34,112,97,121,108,111,97,100,34,58,110,117,108,108,125'

我想这是JSON对象,但我怎样才能将它转换为可读格式?

最佳答案
最有可能的消息是以错误的格式(字符串化的字节数组)发送的,因此您将获得这种形式的消息.修改发件人或将其转换为正确的字符串.

    String str = "123,34,97,99,116,105,111,110,34,58,34,103,101,116,73,110,102,111,34,44,34,114,101,115,117,108,116,34,58,34,78,111,116,82,101,103,105,115,116,101,114,101,100,34,44,34,112,97,121,108,111,97,100,34,58,110,117,108,108,125";
    String[] chars = str.split(",");
    StringBuilder builder = new StringBuilder();
    Arrays.asList(chars).stream().map(Byte::valueOf).forEach(b -> builder.append((char)b.byteValue()));
    System.out.println(builder.toString());

whitch输出

{“action”:”getInfo”,”result”:”NotRegistered”,”payload”:null}

转载注明原文:如何在Spring AMQP中解析JSON对象? - 代码日志