levshkatov levshkatov - 3 months ago 18
Android Question

"Unexpected token o" in JSON

I have an android app where I'm trying to send data from editText to server. I'm trying to pack data to JSON:

editTextLogin = (EditText) findViewById(R.id.editTextLogin);
editTextPass = (EditText) findViewById(R.id.editTextPass);
JSONObject logPass = new JSONObject();
try {
logPass.put("login", editTextLogin.getText().toString());
logPass.put("pass", editTextPass.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("logPass", logPass);


After that I receive these data on server and try to parse it to JS object:

socket.on('logPass', function(dataJSON) {
console.log(dataJSON.admin);
data = JSON.parse(dataJSON);
});


I can print dataJSON, it is:
( login: 'admin', pass: '1234' )
but when I'm trying to parse it I have error:
Unexpected token o


What's it and how to solve it?

Answer
import org.json.simple.JSONObject;

class JsonDemo {

   public static void main(String[] args){
      JSONObject obj = new JSONObject();

      obj.put("login", "admin");
      obj.put("pass", "admin123");

      System.out.print(obj);
   }
}

OR

import org.json.simple.JSONObject;

class JsonDemo {

   public static void main(String[] args){

      JSONObject obj = new JSONObject();

      obj.put("login","admin");
      obj.put("pass","admin123");

      StringWriter out = new StringWriter();
      obj.writeJSONString(out);

      String jsonText = out.toString();
      System.out.print(jsonText);
   }
}

OUTPUT

{"login": "admin", "pass":"admin123"}

Bug Issue

mSocket.emit("logPass", logPass.toString());

I hae tried this is working..