N
N
nikesport2014-11-21 10:30:17
Java
nikesport, 2014-11-21 10:30:17

How to compare the string received after parsing with json with a regular string?

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import javax.xml.crypto.Data;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ComplexSocketServer {
public static void main(String args[]) throws Exception {
ServerSocket servSocket;
Socket fromClientSocket;
int cTosPortNumber = 3232;
String str;
ComplexCompany comp;
servSocket = new ServerSocket(cTosPortNumber);
System.out.println("Waiting for a connection on " + cTosPortNumber);
Socket si = servSocket.accept();
System.out.print("Connected");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(si.getOutputStream());
DataInputStream ois = new DataInputStream(si.getInputStream());
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson((String) ois.readUTF(), JsonObject.class);
String number = jsonObject.get("KEY").toString();
System.out.println(number);
String strr = "CHECK_MESSAGE";
if (number == strr){
System.out.println(number);
}
the contents of both string variables CHECK_MESSAGE but they are not compared in any way, if does not find a match between number and strr, what is the reason I can not understand?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
F
Fedor Kolov, 2014-11-21
@d_f

Maybe because you should first learn the basics of Java and understand that through == the addresses of strings are compared, and not the strings themselves?
To compare strings, you need to rewrite the condition:
if (number.equals(strr)){

S
Sergey, 2014-11-21
Protko @Fesor

We put a break in the code, we look at what is actually contained in the variables, we are looking for an error.

D
Dmitry, 2014-11-21
@CTAKAH4uK

Comparison only through equals, apparently the encoding is different, or the DataInputStream adds the end of the string or something else

String number = new String(jsonObject.get("KEY").toString().getBytes(), "UTF-8");
String strr = new String("CHECK_MESSAGE".getBytes(), "UTF-8");

Y
YV, 2014-11-21
@targetjump

Use equals, if the strings "look the same" and at the same time they are not equals, then compare the bytes of the strings and you will see that they are different.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question