byte[] to string conversion

97 views Asked by At

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

There are 1 answers

0
Abhishek Patidar On BEST ANSWER

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);
}