dongtuan5367 2014-11-27 23:09
浏览 41
已采纳

byte []到字符串转换

Hiii,

I am using Gearman to handle communication between PHP and java. I am trying to send array from PHP using json_encode to java worker. At php Side:

public function test()
{
    $test = $this->serviceManager->get('test\Model\test');
    //print_r($test);exit;
    $message = array(
        'to'        =>  'abhi',
        'message'   =>  'this is a test',
    );
    $test->sendtoJavaWorker(json_encode($message));
}

At java side:

@Override
public byte[] work(String function, byte[] data, GearmanFunctionCallback callback) throws Exception {

    String json = new String(data, "UTF-8");

    JSONObject jsonObject = new JSONObject(String.valueOf(json)); 

    String to = (String) jsonObject.get("to");

    return data;
}

Now I am getting json value as shown in picture like ""{\"to\":\"abhi\",\"message\":\"this is a test\"}"". Can someone help.

enter image description here

For time being, I m fixing this by using this code

String json = new String(data);
    json = json.toString().replace("\\", "");
    StringBuilder sb = new StringBuilder(json);
    sb.deleteCharAt(0);
    sb.deleteCharAt(sb.length()-1);
    json = sb.toString();

    System.out.println(json);

And then I am getting answer like:

enter image description here

展开全部

  • 写回答

1条回答 默认 最新

  • dqphg40600 2014-11-28 00:18
    关注

    Hiii, I got the answer, I was sending array after using json_encode to gearman, turns out sending directly to it worked.

    public function test()
    {
        $test = $this->serviceManager->get('test\Model\test');
        //print_r($test);exit;
        $message = array(
            'to'        =>  'abhi',
            'message'   =>  'this is a test',
        );
        $test->sendtoJavaWorker($message);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部