How to read json file into java with jackson library? - java

I want to read this simple JSONfile with java jackson library(I'm new to JSON).
Coud you please tell to me what i do wrong?I created class or JSON object wrongly or this metod of convertion JSON object to Java is wrong, thanks
Edit now i get set of exception like this
This is what the JSONfile stores
{
"id": 15,
"name": "Steve",
"Datax": {
"veek": "vect",
"seev": "vecs"
}
}
And i have three classes
Here is a Cevan:
public class Cevan {
private int id;
private String name;
private Datax data;
public Datax getData() {
return data;
}
public void setData(Datax data) {
this.data = data;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
and Datax:
public class Datax {
private String veek;
private String seev;
public String getSeev() {
return seev;
}
public String getVeek() {
return veek;
}
public void setSeev(String seev) {
this.seev = seev;
}
public void setVeek(String veek) {
this.veek = veek;
}
}
and Class Main:
public class Main {
public static void main(String[] args) throws IOException {
ObjectMapper mapper=new ObjectMapper();
InputStream is= Cevan.class.getClassLoader().getResourceAsStream("json2.json");
Cevan testObj = mapper.readValue(is, Cevan.class);
}
}
It's like my project looks

Change your resourseStreamReader from
InputStream is=Cevan.class.getResourceAsStream("json2.json");
to:
InputStream is = this.getClassLoader().getResourceAsStream("json2.json");
and also make sure what your json2.json is in classpath

It should be nice to have the log files attached as text and not as image.
The problem should be in the json file.
According to your java classes the json file should be as follows:
{
"id": 15,
"name": "Steve",
"data": {
"veek": "vect",
"seev": "vecs"
}
}
Note the object attribute change from "Datax" to "data".

Related

JSON serialize to a different value

I have the below json which im serializing
{
"name":"John",
"switch":"1"
},
{
"name":"Jim",
"switch":"0"
}
I want to serialize it to a differnt name So I had to do it like below
class Data {
private String name;
private String flag;
#JsonProperty("flag")
public byte getFlag() {
return flag;
}
#JsonProperty("switch")
public void setSwitch(String s) {
this.flag = flag;
}
}
So that I get it converted as below
{
"name":"John",
"flag":"1"
},
{
"name":"Jim",
"flag":"0"
}
Now I wanted to map the numic values to Y and N for 1 and 0 respectively. Can I acheive that ?
Im expecting my final string to be like this
{
"name":"John",
"switch":"Y"
},
{
"name":"Jim",
"switch":"N"
}
I agree with #Gaƫl J, but still if you want to go ahead this code change might help you to convert that 1/0 to Y/N.
public class Application {
#ToString
static class Input {
#JsonProperty("name")
private String name;
#JsonProperty("switch")
private String flag;
#JsonProperty("name")
public void setName(String name){
this.name = name;
}
#JsonProperty("switch")
public void setSwitch(String s) {
for(SwitchMap valuePair : SwitchMap.values()){
if(valuePair.getValue().equals(s)){
this.flag = valuePair.name();
}
}
}
}
public static void main(String[] args) throws JsonProcessingException {
String json = "{\n" +
"\"name\":\"John\",\n" +
"\"switch\":\"1\"\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
Input in = mapper.readValue(json, Input.class);
System.out.println(mapper.writeValueAsString(in));
}
}
define an enum with the mapping
#Getter
public enum SwitchMap {
Y("1"),
N("0");
private final String value;
private SwitchMap(String value){
this.value = value;
}
}

UnrecognizedPropertyException: Unrecognized field "sections"

I'm using Jackson as part of a spring boot app. I am turning JSON into Java, and I am getting this error. I did some research, but I still don't understand what is going wrong or how to fix it.
Here is the JSON fragment:
"dataBlock": {
"sections": [
{
"info": "",
"prompt": "",
"name": "First Section",
"sequence": 0,
"fields": [],
"gatingConditions": [],
"guid": "480d160c-c34f-4022-97b0-e8a1f28c49ae",
"id": -2
}
],
"prompt": "",
"id": -1,
"name": ""
}
So my Java object for this "dataBlock" element:
public class DataBlockObject {
private int id;
private String prompt;
private String name;
private List<SectionObject> sections;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<SectionObject> getSections() {
return sections;
}
public void setSections(List<SectionObject> sections) {
this.sections = sections;
}
}
And the Section object is this:
public class SectionObject {
private int id;
private String name;
private String prompt;
private String info;
private int sequence;
private List<FieldObject> fields;
private List<GatingConditionObject> gatingConditions;
private String guid;
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;
}
public String getPrompt() {
return prompt;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
public List<FieldObject> getFields() {
return fields;
}
public void setFields(List<FieldObject> fields) {
this.fields = fields;
}
public List<GatingConditionObject> getGatingConditions() {
return gatingConditions;
}
public void setGatingConditions(List<GatingConditionObject> gatingConditions) {
this.gatingConditions = gatingConditions;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
}
So it seems to me that Jackson would make a DataBlockObject, map the obvious elemenets, and create an array that I have clearly marked as a List named sections. -- just like the JSON shows.
Now the error is:
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "sections" (class com.gridunity.workflow.bean.json.SectionObject), not marked as ignorable (8 known properties: "gatingConditions", "sequence", "prompt", "fields", "id", "info", "guid", "name"])
Now according to that error it would seem that one of my 8 elements should be named "sections" - But that's not one of my elements. It clearly has a problem with my List of Sections, but I cant figure out what it is.
Can someone explain WHY this is happening, especially sence it looks like I have my structure correct, and how to fix this. I have seen this on other posts:
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
But that seems incredibly wrong as I know all of my properties.
It looks like the JSON itself has another sections field in one or more of the dataBlock.sections items. If you don't have control over the construction of the JSON object, you'll need to add a #JsonIgnoreProperties annotation on the SectionObject class so that when the JSON object has fields that aren't specified in the POJO, it won't throw an error during deserialization.
#JsonIgnoreProperties(ignoreUnknown = true)
public class SectionObject {
// class members and methods here
}

Binding json, that has a list, with an object using Jackson

Given I have the following json:
{
"Company": {
"name": "cookieltd",
"type": "food",
"franchise_location": [
{
"location_type": "town",
"address_1": "5street"
},
{
"location_type": "village",
"address_1": "2road"
}
]
}
}
How can it be binded to the following object classes using Jackson?:
1) Company class
public class Company
{
String name, type;
List<Location> franchise_location = new ArrayList<Location>();
[getters and setters]
}
2) Location class
public class Location
{
String location_type, address_1;
[getters and setters]
}
I have done:
String content = [json above];
ObjectReader reader = mapper.reader(Company.class).withRootName("Company"); //read after the root name
Company company = reader.readValue(content);
but I am getting:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "franchise_location"
As far as I can tell, you are simply missing an appropriately named getter for the field franchise_location. It should be
public List<Location> getFranchise_location() {
return franchise_location;
}
(and the setter)
public void setFranchise_location(List<Location> franchise_location) {
this.franchise_location = franchise_location;
}
Alternatively, you can annotate your current getter or field with
#JsonProperty("franchise_location")
private List<Location> franchiseLocation = ...;
which helps to map JSON element names that don't really work with Java field name conventions.
The following works for me
public static void main(String[] args) throws Exception {
String json = "{ \"Company\": { \"name\": \"cookieltd\", \"type\": \"food\", \"franchise_location\": [ { \"location_type\": \"town\", \"address_1\": \"5street\" }, { \"location_type\": \"village\", \"address_1\": \"2road\" } ] } }";
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader(Company.class).withRootName(
"Company"); // read after the root name
Company company = reader.readValue(json);
System.out.println(company.getFranchise_location().get(0).getAddress_1());
}
public static class Company {
private String name;
private String type;
private List<Location> franchise_location = new ArrayList<Location>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Location> getFranchise_location() {
return franchise_location;
}
public void setFranchise_location(List<Location> franchise_location) {
this.franchise_location = franchise_location;
}
}
public static class Location {
private String location_type;
private String address_1;
public String getLocation_type() {
return location_type;
}
public void setLocation_type(String location_type) {
this.location_type = location_type;
}
public String getAddress_1() {
return address_1;
}
public void setAddress_1(String address_1) {
this.address_1 = address_1;
}
}
and prints
5street
my solution for JSON is always GSON, you can do some research on that, as long as you have the correct structure of class according to the JSON, it can automatically transfer from JSON to object:
Company company = gson.fromJson(json, Company.class);
GSON is so smart to do the convertion thing!
enjoy GSON !

Json Structure is So Different unable to change that to Java Objects

I am working on facebook application. When i queried for https://graph.facebook.com/me/video.watches?offset=0&limit=1000 I am getting a List of Watched Movies. For eg. I am pasting only one movie out of that list here.
{
"data": [
{
"id": "664878940211923",
"data": {
"tv_show": {
"id": "108611845829948",
"url": "https://www.facebook.com/pages/Popeye-the-Sailor/108611845829948",
"type": "video.tv_show",
"title": "Popeye the Sailor"
}
},
"type": "video.watches",
},
Here is the POJO Class I created to convert this to Java.
import java.util.List;
public class FBUserVideoWatches {
private List<Data> data;
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
public class Data{
private long id;
private TVData data;
private String type;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public TVData getData() {
return data;
}
public void setData(TVData data) {
this.data = data;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class TVData{
private TV_Shows tv_shows;
public TV_Shows getTv_shows() {
return tv_shows;
}
public void setTv_shows(TV_Shows tv_shows) {
this.tv_shows = tv_shows;
}
}
public class TV_Shows{
private long id;
private String url;
private String type;
private String title;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}
Here is how i convert the json to java.
FBUserVideoWatches fbUserVideoWatches = gson.fromJson(response.getBody(), FBUserVideoWatches.class);
for (Data data : fbUserVideoWatches.getData()) {
System.out.println(data.getId());//This only works and I am getting values.
if(null != data.getData()){
if(null!=data.getData().getTv_shows()){
System.out.print(data.getData().getTv_shows().getTitle());
}
if(null!=data.getData().getTv_shows()){
System.out.print(data.getData().getTv_shows().getType());
}
}
}
When I use getter methods to get data from java class I am getting ID 664878940211923 & "type": "video.watches" as shown above. The members inside "tv_show" I am unable to access. I think some where I went wrong in creating POJO. I am unable to find that mistake. Please help me what corrections is necessary to make that work. Hope my question is clear. Thanks in Advance.
You were doing mistake in TVData Class your forgot serialized name on instance property coz its in diffferent in json and TV data class
#SerializedName(value="tv_show")
private TV_Shows tv_shows;
Assuming your json is like this
{
"data":[
{
"id":"664878940211923",
"data":{
"tv_show":{
"id":"108611845829948",
"url":"https://www.facebook.com/pages/Popeye-the-Sailor/108611845829948",
"type":"video.tv_show",
"title":"Popeye the Sailor"
}
},
"type":"video.watches"
},
{
"id":"664878940211923",
"data":{
"tv_show":{
"id":"108611845829948",
"url":"https://www.facebook.com/pages/Popeye-the-Sailor/108611845829948",
"type":"video.tv_show",
"title":"Popeye the Sailor"
}
},
"type":"video.watches"
}
]
}
Parsing model will like below according you to your json format
public class FBUserVideoWatches {
private List<Data> data;
public List<Data> getData() { return data; }
public void setData(List<Data> data) { this.data = data;}
}
public class Data {
private TVData data;
private String id;
private String type;
// setter/getter here
}
public class TVData {
#SerializedName(value="tv_show")
private Show show;
// setter/getter here
}
public class Show {
private String id;
private String url;
private String type;
private String title;
// setter/getter here
}
finally with Google Gson parse your object as like below
Gson gson = new Gson();
FBUserVideoWatches fbUserVideoWatches =gson.fromJson(json_string, FBUserVideoWatches.class);

Android Json/Gson issue

I am having trouble with this json.
{"directory": {
"employees": {"employee": [
{
"field": [
{
"content": "Charlotte Abbott",
"id": "displayName"
},
{
"content": "Charlotte",
"id": "firstName"
},
I am casting it into a class that looks like this
#SerializedName("directory")
public Directory directory;
public class Directory
{
#SerializedName("employees")
public Employees employees;
}
public class Employees
{
#SerializedName("employee")
public List<Employee> employee;
}
public class Employee
{
#SerializedName("field")
public List<Fields> fields;
#SerializedName("id")
public String employeeId;
}
public class Fields
{
#SerializedName("content")
public String content;
#SerializedName("id")
public String label;
}
And it is not reaching all the variables to insert the data when it serializes. Instead I am getting all nulls. I am however getting the right amount (number) of Directory objects so I know it is reaching that far. Anyone have some insight on what I am doing wrong here? The json is the way it is, I didn't design it, but it is how it is used.
Quite a weird data structure you have to work with, but here is it.
public class App {
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = "{\"directory\": {\"employees\": {\"employee\": [{\"field\": [{\"content\": \"Charlotte Abbott\",\"id\": \"displayName\"},{\"content\": \"Charlotte\",\"id\": \"firstName\"}]}]}}}";
Wrapper obj = (Wrapper) gson.fromJson(jsonString, Wrapper.class);
System.out.println(obj.getDirectory().getEmployees().getEmployeeList()
.get(0).getFieldList().get(0).getContent());
}
}
You need a Wrapper class to wrap around Directory.
public class Wrapper {
private Directory directory;
public Directory getDirectory() {
return directory;
}
public void setDirectory(Directory directory) {
this.directory = directory;
}
}
Directory class.
public class Directory {
#SerializedName("employees")
private Employees employees;
public Employees getEmployees() {
return employees;
}
public void setEmployees(Employees employees) {
this.employees = employees;
}
}
Employees class:
public class Employees {
#SerializedName("employee")
private List<Employee> employeeList;
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
}
Employee class:
public class Employee {
#SerializedName("field")
private List<Field> fieldList;
public List<Field> getFieldList() {
return fieldList;
}
public void setFieldList(List<Field> fieldList) {
this.fieldList = fieldList;
}
}
Field class:
public class Field {
#SerializedName("content")
private String content;
#SerializedName("id")
private String id;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
See a JSON to Java Object using GSON example here: http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/
So here is how it worked out, i had it right, i just wasn't validating the data correctly after it was being put in, and so I was losing it by not being able to assign it and store it for later access.
It is ugly but the map looks like this
DIRECTORY obj
{
EMPLOYEES obj
{
List employee []
{
int id
List fields[]
{
content
id
{
{
{
{

Categories

Resources