Java gson arrays of arrays: java.lang.IllegalStateException - java

I am trying to deserialize the following JSON:
[{
"customerDetails":
{
"customer_name": "name",
"customer_email": "email"
},
"shippingD‌​etails":
{
"shipping_contact": "name",
"shipping_street": "Av:"
}
}]
Array
(
[0] => Array
(
[customerDetails] => Array
(
[customer_name] => name
[customer_email] => email
)
[shippingDetails] => Array
(
[shipping_contact] => shipname
[shipping_street] => Av:Name
)
)
)
Heres my classes:
public class Order {
private List<CustomerDetail> customerDetail;
private List<Shipping> shipping;
//getters and setters
}
public class Shipping {
private String contact;
private String street;
//getters and setters
}
public class CustomerDetail{
private String name;
private String email;
//getters and setters
}
I tried this:
Gson g = new Gson();
Order[] order = g.fromJson(new FileReader("jason"), Order[].class);
List <CustomerDetail> cd = order[0].getCustomerDetail();
System.out.println(cd.get(0).getName());
But I keep gettin either NullPointer or
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

You Java doesn't match the JSON, and the error message is telling you that you're trying to parse an object rather than an array (although, the code you show using Gson wouldn't throw the exception). I'm also not sure what the thing you show under your JSON is, because it bears no resemblance to the JSON either.
Your JSON is an array. That array contains an object (presumably you're expecting it to have many of these, but as-is it shows one). That object has two fields; customerDetails and shippingD‌​etails that each hold another object.
Your Orders class would need to be:
public class Orders {
private CustomerDetail customerDetails;
private Shipping shippingDetails;
}
(and given that it looks like that's a single order, I'd drop the plural and name the class Order)
You can then parse that JSON with Gson via:
Orders[] orders = new Gson().fromJson(myJson, Orders[].class);

Related

in java convert json object where parameter name is a value to a java opject or jpa entity [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 11 months ago.
basically taking in a json object via a post api thats like the following
{
[
param_name: "name",
param_value: "jason"
param_type: "varchar"
],
[
param_name: "age",
param_value: "15"
param_type: "varchar"
]
}
then i want to convert it to a predefined java object where the parameter names are the same as the "param_value" values.
Is there anyway to do this in java, with a method like this?
student.setparamname(object.get("param_name"),object.get("param_value") );
You would want something like this if my interpretation of your question is correct. This allows you to POST to the endpoint with an object and specify name and age in json format. I'm going to say that the above is a Student for example but that's just an example object. If you want to include validation have a look at using #Valid. What you've declared in the question is a JsonArray (indicated by the [] after the {}) within a JsonObject but there is no need for that, just create the JsonObject with the fields you require.
#JsonDeserialize(builder = NewStudent.Builder.class)
public class NewStudent{
private String name;
private String age;
//getters and setters here
//create builder here
}
public class Student{
private String name;
private String age;
//getters and setters here
}
#PostMapping(value = "/addstudent", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Student> createStudent(#RequestBody NewStudent newStudent){
Student student = new Student();
student.setName(newStudent.getName());
student.setAge(newStudent.getAge());
ResponseEntity<Student> responseContent = ResponseEntity.body(student);
return responseContent;
}

How to Parse JSON object partially to Java object

I am working on a big json output file which is coming as response but I want to parse only some of the fields in my logic.
For ex: The JSON looks like this
{
"lastName":"Smith",
"address":{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":10021
},
"age":25,
"phoneNumbers":[
{
"type":"home", "number":"212 555-1234"
},
{
"type":"fax", "number":"212 555-1234"
}
],
"firstName":"John"
}
I have created the necessary JAVA classes and mapping the JSON Object to Java object using GSON. Since, the above JSON is just a sample one in my case I have big one which is generating around 15 classes.
Currently i have to create following classes files:
- Employee.class
- Address.class
- PhoneNumber.class
I want to avoid creating PhoneNumber.class and its nested class using GSON.
Basically My query is like in above json I don't want phoneNumbers and its internal objects so how can i ignore those fields so that i have to construct less Java Class files and still it is mapped to Java Object.
So I want to avoid making classes for PhoneNumbers fields and the nested fields inside PhoneNumbers.
As suggested, Employee and Address classes are all you need:
public class Employee {
private String firstName, lastName;
private int age;
private Address address;
}
public class Address {
private String streetAddress, city, state;
private int postalCode;
}
new Gson().fromJson(json, Employee.class);, where json is the raw JSON string, should then do what you want. Without sharing your code, it is hard to tell why it doesn't work for you.

Changing JSON array to to a pojo object array

I am getting API response on the following format. I am working on Android project
{
Course: [
{
"Year": 2017,
"CourseTitle": "..",
"Quarter": "autumn",
},
{
"Year": 2017,
"CourseTitle": "..",
"Quarter": "autumn",
}
],
Instructor: {
"name": ,
"address":
}
}
My goal is to get Course array of courses, and assign it to the POJO (plain old java object) that I created using online tool. I am also using the GSON library. I did find different implementation online, and I finally used this, and I was able to filter the nested object "Courses", which holds an array object of courses.
JsonParser parser = new JsonParser();
JsonObject element = (JsonObject)parser.parse(response);
JsonElement responseWrapper = element.getAsJsonArray("Courses");
When I look responseWrapper using debugger tool, it holds a JSON array of course (objects). I wanted to assign these data to the "Course" POJO class I created
public class Course implements Parcelable {
private String href;
private int year;
private String courseTitle;
private String quarter;
private String courseTitleLong;
private String curriculumAbbreviation;
private String courseNumber;
}
I added the following line.
Course[] courseList = gson.fromJson(responseWrapper,Course[].class);
CourseList is an array of Course object, but when I look what I got using debugger tool all the field variables are "null". How could I solve this problem? Is there a better way I should have approached? The whole purpose is getting array of course objects so I could manipulate it for display.
Try to rename your fields to exactly match the json response, even case-wise.

GSON get string from complex json

I am trying to parse the JSON from this link: https://api.guildwars2.com/v2/items/56 , everything fine until i met the line: "infix_upgrade":{"attributes":[{"attribute":"Power","modifier":4},{"attribute":"Precision","modifier":3}]} ...
If i dont get this wrong: infix_upgradehas 1 element attributes inside him. attributes has 2 elements with 2 other inside them. Is this a 2 dimension array?
I have tried (code too long to post):
JsonObject _detailsObject = _rootObject.get("details").getAsJsonObject();
JsonObject infix_upgradeObject = _detailsObject.get("infix_upgrade").getAsJsonObject();
JsonElement _infix_upgrade_attributesElement = infix_upgradeObject.get("attributes");
JsonArray _infix_upgrade_attributesJsonArray = _infix_upgrade_attributesElement.getAsJsonArray();
The problem is that I dont know what to do next, also tried to continue transforming JsonArray into string array like this:
Type _listType = new TypeToken<List<String>>() {}.getType();
List<String> _details_infusion_slotsStringArray = new Gson().fromJson(_infix_upgrade_attributesJsonArray, _listType);
but im getting java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT which i guess comes from the attributes...
With a proper formatting (JSONLint, for example, checks if the JSON data is valid and does the formatting, which makes the structure more clear than what the GW link gives), attributes looks actually like this:
"attributes": [
{
"attribute": "Power",
"modifier": 4
},
{
"attribute": "Precision",
"modifier": 3
}
]
So it's an array of JsonObject and each object as two key-value pairs. This is why the parser throws an error because you require that this array contains only String which is not the case.
So the actual type is:
Type _listType = new TypeToken<List<JsonObject>>(){}.getType();
The problem is that I dont know what to do next
Hold on. You are using Gson and Java is an OO language so I suggest you to create classes.
This would be easier for you to fetch the datas afterward and for the parsing since you just need to provide the class of the actual class the JSON data represents to the parser (some edge-cases could be handled by writing a custom serializer/deserializer).
The data is also better typed than this bunch of JsonObject/JsonArray/etc.
This will give you a good starting point:
class Equipment {
private String name;
private String description;
...
#SerializedName("game_types")
private List<String> gameTypes;
...
private Details details;
...
}
class Details {
...
#SerializedName("infix_upgrade")
private InfixUpgrade infixUpgrade;
...
}
class InfixUpgrade {
private List<Attribute> attributes;
...
}
class Attribute {
private String attribute;
private int modifier;
...
}
and then just give the type to the parser:
Equipment equipment = new Gson().fromJson(jsonString, Equipment.class);
Hope it helps! :)

desrialize JSON with child array using Jackson annotations?

I'm trying to parse some JSON containing a nested array. I'd like the array to map to a list of child objects within the parent I'm mapping. Here is the (slightly abbreviated) JSON and Java classes
JSON:
{
"id": "12121212121",
"title": "Test Object",
"media$content": [
{
"plfile$audioChannels": 1,
"plfile$audioSampleRate": 18000,
},
{
"plfile$audioChannels": 2,
"plfile$audioSampleRate": 48000,
},
{
"plfile$audioChannels": 2,
"plfile$audioSampleRate": 48000,
}
]
}
Java classes
class MediaObject {
#JsonProperty("id")
private String id;
#JsonProperty("title")
private String title;
#JsonProperty("media$Content")
private List<MediaContent> mediaContent;
... getters/setters ...
}
class MediaContent {
#JsonProperty("plfile$audioChannels")
private int audioChannels;
#JsonProperty("plfile$audioSampleRate")
private int audioSampleRate;
... getters/setters ...
}
I'd like to be able to deserialize using annotations along with the standard mapper code, i.e.
mapper.readValue(jsonString, MediaObject.class)
Everything works fine with the "id" and "title" fields, but my list of MediaContent objects always comes up null. This seems like something Jackson should be able to handle without much trouble, can anyone see what I'm doing wrong here?
The name of the json field is wrong - the attribute is not media$Content, rather media$[c]ontent. Otherwise I do not see why it will not work.

Categories

Resources