How to Convert a JSON String to an Object

How to convert the following json string to java object?

No need to go with GSON for this; Jackson can do either plain Maps/Lists:

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);

or more convenient JSON Tree:

JsonNode rootNode = mapper.readTree(json);

By the way, there is no reason why you could not actually create Java classes and do it (IMO) more conveniently:

public class Library {
@JsonProperty("libraryname")
public String name;

@JsonProperty("mymusic")
public List<Song> songs;
}
public class Song {
@JsonProperty("Artist Name") public String artistName;
@JsonProperty("Song Name") public String songName;
}

Library lib = mapper.readValue(jsonString, Library.class);

Safely turning a JSON string into an object

JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.

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 JSON string into List of Java object?

You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

how to convert json string back to an object in Angular 8

You can do it with JSON.parse.

  const obj = JSON.parse(subjects);
console.log(obj.subject1); // "A"

Converting a string to JSON object

var obj = JSON.parse(string);

Where string is your json string.

How to convert Java String to JSON Object

You are passing into the JSONObject constructor an instance of a StringBuilder class.

This is using the JSONObject(Object) constructor, not the JSONObject(String) one.

Your code should be:

JSONObject jsonObj = new JSONObject(jsonString.toString());

Convert JSON String To C# Object

It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.

For instance:

  class Test {

String test;

String getTest() { return test; }
void setTest(String test) { this.test = test; }

}

Then your deserialization code would be:

   JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");

More information can be found in this tutorial:
http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx



Related Topics



Leave a reply



Submit