我有字符串
{"version":"T2"}
我从 webview 读取它并将其存储在变量 s 中。
我想解析版本的值。所以
try {
s= s.replaceAll("\n", "\\n");
JSONObject json = new JSONObject(s);
Log.d("SAVE_LOG", (String) json.get("version"));
} catch (JSONException e) {
Log.d("SAVE_LOG", String.valueOf(e));
e.printStackTrace();
}
我从每个网站都找到了这个代码。
但它给了我这个错误。
org.json.JSONException: Value {"version":"T2"} of type java.lang.String cannot be converted to JSONObject
我的进口是
import android.Manifest;
import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
import com.tcn.liftboard.control.PayMethod;
import com.tcn.liftboard.control.TcnVendEventID;
import com.tcn.liftboard.control.TcnVendEventResultID;
import com.tcn.liftboard.control.TcnVendIF;
import com.tcn.liftboard.control.VendEventInfo;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
最佳答案
这是我的代码
import org.json.JSONException;
import org.json.JSONObject;
public class NewClass {
public static void main(String[] args) {
try {
String s = "{\"version\":\"T2\"}";
s= s.replaceAll("\n", "\\n");
JSONObject jsonObject = new JSONObject(s);
System.out.println(jsonObject.get("version"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
输出:
T2
从 JSON jar download from maven 导入 json jar 文件
关于java - 在JAVA中解析stringify字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61017654/