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);
How to convert the following JSON String to POJO
I think it should work. I've executed this code and it works fine. Here is my example.
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class TestJackson {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String testJson = "{\n" + " \"user\": {\n" + " \"0\": {\n" + " \"firstName\": \"Monica\",\n" + " \"lastName\": \"Belluci\"\n" + " },\n" + " \"1\": {\n" + " \"firstName\": \"John\",\n" + " \"lastName\": \"Smith\"\n" + " },\n" + " \"2\": {\n" + " \"firstName\": \"Owen\",\n" + " \"lastName\": \"Hargreaves\"\n" + " }\n" + " }\n" + "}";
User readValue = mapper.readValue(testJson, User.class);
System.out.println("readValue = " + readValue);
}
}
and the User.class:
import java.util.HashMap;
import java.util.Map;
class User {
private Map<String, MyObject> user = new HashMap<String, MyObject>();
public Map<String, MyObject> getUser() {
return user;
}
public void setUser(Map<String, MyObject> user) {
this.user = user;
}
@Override
public String toString() {
return "User{" +
"user=" + user +
'}';
}
}
class MyObject {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "MyObject{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Converting JSON data to Java object
I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?
Google Gson supports generics and nested beans. The []
in JSON represents an array and should map to a Java collection such as List
or just a plain Java array. The {}
in JSON represents an object and should map to a Java Map
or just some JavaBean class.
You have a JSON object with several properties of which the groups
property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson()
.
See also:
- Json.org - Introduction to JSON
- Gson User Guide - Introduction to Gson
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>>(){});
Convert a JSON string to object in Java ME?
I used a few of them and my favorite is,
http://code.google.com/p/json-simple/
The library is very small so it's perfect for J2ME.
You can parse JSON into Java object in one line like this,
JSONObject json = (JSONObject)new JSONParser().parse("{\"name\":\"MyNode\", \"width\":200, \"height\":100}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("width"));
How to convert JSON to Java object?
user ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);
Check This Link
JSON String to Java object with JSON string key rename
You just need to add @JsonProperty
in both setter and getters.
In your case,
You are reading JSON string key FST_NME
, so you need to add @JsonProperty('FST_NME')
in the setter method for firstName
and as you want to get the final JSON string with key firstName
so you need to add @JsonProperty('firstName')
in the getter method of firstName
.
And same for lastName
.
Following is the working code.
package com.ubaid.stackoverflow;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Saravanan {
@SneakyThrows
public static void main(String[] args) {
ObjectMapper MAPPER = new ObjectMapper();
String jsonString = "{\"FST_NME\":\"stack\",\"LST_NME\":\"OVERFLOW\"}";
Person person = MAPPER.readValue(jsonString, Person.class);
String finalJson = MAPPER.writeValueAsString(person);
log.debug("Final JSON: {}", finalJson);
}
}
class Person {
private String firstName;
private String lastName;
@JsonProperty("firstName")
public String getFirstName() {
return firstName;
}
@JsonProperty("FST_NME")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@JsonProperty("lastName")
public String getLastName() {
return lastName;
}
@JsonProperty("LST_NME")
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
The output of above code is:
Final JSON: {"firstName":"stack","lastName":"OVERFLOW"}
Related Topics
Ionic Build Android Error When Downloading Gradle
How to Use Vectordrawable in Buttons and Textviews Using Android:Drawableright
How to Connect to Ftps Server with Data Connection Using Same Tls Session
Expected Begin_Array But Was Begin_Object at Line 1 Column 2
How to Achieve Javafx Mouse Event "Push and Hold"
Installing Oracle Jdk on Windows Subsystem for Linux
Firebase Firestore Get Data from Collection
I Would Like to Set My Variables at the Top of My Class Instead of in the Method
How Do Jps, Jinfo, Jstat, Jmap and Jstack Get Information About Local Java Processes
How to Find Java Heap Size and Memory Used (Linux)
What Happens When I Throw a C++ Exception from a Native Java Method
Access Restriction: the Type 'Application' Is Not API (Restriction on Required Library Rt.Jar)
Detect Touch Press VS Long Press VS Movement
How to Convert an Int Array to String with Tostring Method in Java