How to Convert String to Json Object in Java?

There are following way to Convert String to Json Object in Java.

  • Here we are creating three class Student, StudentDepartment and ConvertStringToJson.
  • Create Student class with id and name.
  • Create StudentDepartment class with branch and name.
  • Here stringToJsonData() method take two input student.getName() as String and  StudentDepartment.class use to pass String into json data.
  • Now mapper.readValue(string, clazz) method convert String data to json format.
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

class Student {
	int id;
	String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

class StudentDepartment {

	@JsonProperty("branch")
	String branch;
	@JsonProperty("name")
	String name;

	public String getBranch() {
		return branch;
	}

	public void setBranch(String branch) {
		this.branch = branch;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	
}

public class ConvertStringToJson {
	public static void main(String[] args) {
		Student student = null;
		StudentDepartment studentDepartment;
		try {
			studentDepartment = stringToJsonData(student.getName(), StudentDepartment.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static <JSON_Object> JSON_Object stringToJsonData(String string, Class<JSON_Object> clazz)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(string, clazz);
	}
}