Conversion from String to JSON Object Android

conversion from string to JSON object Android

Remove the slashes:

String json = {"phonetype":"N95","cat":"WP"};

try {

JSONObject obj = new JSONObject(json);

Log.d("My App", obj.toString());

} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}

Android Convert String to JSONObject

If you really want it to be formatted like that then make it into a string instead of a number. Just add double quotes around the item. But if your using it for a calculation on the other end, i would leave it as is as you'll have to convert it back to a int anyway. If you want to use gson as an alternative check here: How to prevent Gson from converting a long number (a json string ) to scientific notation format?

How to convert jsonString to JSONObject in Java

Using org.json library:

try {
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
Log.d("Error", err.toString());
}

How to convert String to JSON Object in Kotlin Android

I have got the solution.

The problem was in my script in webview.

What I did was

doneButton.setOnClickListener{
var view=it
webView.evaluateJavascript(
"JSON.parse(document.getElementById('formio-submitted-data').textContent)"
) { value ->
if(value.length!=2){

val resp: JsonObject = JsonParser().parse(value).asJsonObject
val jsonObject = JsonObject()
jsonObject.add("data", resp)

I have changed the code inside evaluateJavaScript.

How to convert string to json string and object in java

Since it isn't nested, simply add " around : and ,, and after { and before }:

s = s.replaceAll("(?<=[{:,])|(?=[:,}])", "\"");

See demo on regex101.com.

Converting json string to java object?

EDIT:
You need your java Data class to be an exact model of the JSON. So your

{"data":{"translations":[{"translatedText":"Bonjour tout le monde"}]}} 

becomes:

class DataWrapper {
public Data data;

public static DataWrapper fromJson(String s) {
return new Gson().fromJson(s, DataWrapper.class);
}
public String toString() {
return new Gson().toJson(this);
}
}
class Data {
public List<Translation> translations;
}
class Translation {
public String translatedText;
}

As the object model gets more complicated the org.json style code veers towards unreadable whereas the gson/jackson style object mapping is still just plain java objects.

Android - convert json string to JSONObject without removing the escaped characters

You have to use \ escape character before ". Here's what you should do:

{ "length" : "10\"" }

If you have to use special character in your JSON string, you can escape it using \ character.

See this list of special character used in JSON :

\b  Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\\ Backslash character


Related Topics



Leave a reply



Submit