Can not deserialize instance of test.MyPojo out of START_ARRAY token - java

I am not able to convert my JSON to POJO objects.
My JSON output is:
[ {
"id" : 1,
"name" : "latha"
}, {
"id" : 2,
"name" : "kala"
}]
My POJO is:
public class NSCLockData {
private int id;
private 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;
}
}
My class is:
public void insert(org.springframework.messaging.Message<?> msg) throws JsonGenerationException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
try {
MyPojo data=mapper.readValue(msg.getPayload().toString(), MyPojo.class);
this.sessionFactory.getCurrentSession().saveOrUpdate(data);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Create your new POJO so that it should be array of NSLoackData
public class ArrayofNS implements Serialaizable(){
// create serialisation
private List<NSLoackData> arrayof;
// getter and setteers
}
In Your main code where you need to convert the incoming json to your POJO class write something like below
consider u have the above JSON (Array ) in a JSONObject called result;
JSONArray js = new JSOANArray();
convert your above json into JSONArray with the above line of code
js = result;
iterate through the loop and get the value
List<NSLockData> lk = new ArrayList<NSLockData>();
NSLockData data;
for(I=0;i<=js.length();I++){
data = new NSLockDate();
data = new ObjectMapper.readValue(js.get(i).toString(),NSLOckData.class);
lk.add(data);
}

Related

Android fetch volley data from a string of arrays

AM sending a request using android volley and get a response like this
public void onResponse(JSONObject response
try {
String responsedata = response.getString("data");
Log.i("test",responsedata);
} catch (JSONException e) {
e.printStackTrace();
}
}
The above log prints
[{"id":1,"identifier":"TYam Plant","header_val":"tyamplant"},
{"id":2,"identifier":"Touron Plant","header_val":"toroun"}
]
Now i would like to loop through these and extract an array of individual properties that is
id, identifier, header_val
How do i go about this. Am still new to java
You response is JSONArray not JSONObject check it
You need to use JSONArray request instead of JSONObject request of volley
Try this to parse your json
try {
JSONArray jsonArray= new JSONArray(responsedata);
for (int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String id=object.getString("id");
String identifier=object.getString("identifier");
String header_val=object.getString("header_val");
}
} catch (JSONException e) {
e.printStackTrace();
}
Better to Parse your JSON Using google-gson-library
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of
EXAMPLE : How to Parse JSON Array with Gson
You create a Custom Object with 3 field: id, identifier,header_val
public class YourObject {
private String id;
private String identifier;
private String header_val;
public YourObject(String id, String identifier, String header_val) {
this.id = id;
this.identifier = identifier;
this.header_val = header_val;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getHeader_val() {
return header_val;
}
public void setHeader_val(String header_val) {
this.header_val = header_val;
}
}
Loop and add into list: List<YourObject> yourList = new ArrayList<>();
try {
JSONArray jsonArray= new JSONArray(responseString);
for (int i=0; i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String id=object.getString("id");
String identifier=object.getString("identifier");
String header_val=object.getString("header_val");
yourList.add(new YourObject(id, identifier, header_val);
}
} catch (JSONException e) {
e.printStackTrace();
}

Alternate way to create List<MyObject> in #DynamoDBTable without using dynamodbmarshalling (deprecated)

I've followed here by creating the MyCustomMarshaller.
MyCustomMarshaller
public class MyCustomMarshaller implements DynamoDBMarshaller<List<DemoClass>> {
private static final ObjectMapper mapper = new ObjectMapper();
private static final ObjectWriter writer = mapper.writer();
#Override
public String marshall(List<DemoClass> obj) {
try {
return writer.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw failure(e,
"Unable to marshall the instance of " + obj.getClass()
+ "into a string");
}
}
#Override
public List<DemoClass> unmarshall(Class<List<DemoClass>> clazz, String json) {
final CollectionType
type =
mapper.getTypeFactory().constructCollectionType(List.class, DemoClass.class);
try {
return mapper.readValue(json, type);
} catch (Exception e) {
throw failure(e, "Unable to unmarshall the string " + json
+ "into " + clazz);
}
}
}
My dynamoDb class
#DynamoDBAttribute
#DynamoDBMarshalling(marshallerClass = MyCustomMarshaller.class)
List<DemoClass> Object;
DemoClass
public class DemoClass {
String name;
int id;
}
All the codes were working great.By the thing is
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling is
deprecated
So how can I change my code without using this dynamoDBmarshalling?
Thanks in Advance,
Jay
Yes, you should use DynamoDBTypeConverter
You can copy my code from here
For completeness here is the example I used on the linked answer
// Model.java
#DynamoDBTable(tableName = "...")
public class Model {
private String id;
private List<MyObject> objects;
public Model(String id, List<MyObject> objects) {
this.id = id;
this.objects = objects;
}
#DynamoDBHashKey(attributeName = "id")
public String getId() { return this.id; }
public void setId(String id) { this.id = id; }
#DynamoDBTypeConverted(converter = MyObjectConverter.class)
public List<MyObject> getObjects() { return this.objects; }
public void setObjects(List<MyObject> objects) { this.objects = objects; }
}
-
public class MyObjectConverter implements DynamoDBTypeConverter<String, List<MyObject>> {
#Override
public String convert(List<Object> objects) {
//Jackson object mapper
ObjectMapper objectMapper = new ObjectMapper();
try {
String objectsString = objectMapper.writeValueAsString(objects);
return objectsString;
} catch (JsonProcessingException e) {
//do something
}
return null;
}
#Override
public List<Object> unconvert(String objectssString) {
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Object> objects = objectMapper.readValue(objectsString, new TypeReference<List<Object>>(){});
return objects;
} catch (JsonParseException e) {
//do something
} catch (JsonMappingException e) {
//do something
} catch (IOException e) {
//do something
}
return null;
}
}
Another approach that is easier to implement, and you let DynamoDB handle the conversion behind the curtain.
Annotate the field as #DynamoAttribute
#DynamoDBAttribute
private MyObjectClass myObject;
And the, you annotate the "MyObjectClass" with #DynamoDBDocument
#DynamoDBDocument
public class MyObjectClass {
....
}
And DynamoDB will convert and un-convert the "MyObjectClass myObject" to the JSON shape, even if it's a list / array of objects.

Create "tagged" Json Object, instead of just properties

I'm having some problems when i try to deserialize my object into a json string.
I'm getting the following object:
{
"idUser": 1,
"name": "2",
...
}
But I want to achieve this object:
{
"user": {
"idUser": 1,
"name": "2",
...
}
}
I'm serializing my object using this code:
public static String deserializeUser(User user){
ObjectMapper objectMapper = new ObjectMapper();
String json = "";
try {
json = objectMapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
I'm using the api com.fasterxml.jackson
And here goes my User class:
public class User {
public long idUser;
public String name;
public String email;
public String phoneNumber;
#JsonProperty("cpf")
public String CPF;
public String password;
public boolean active;
private String facebookPictureUrl;
private String cameraTakenPhotoBase64;
private String facebookUserId;
... (constructor and getters/setters)
}
That is because you're serializing an instance of User. The intended JSON matches a map with a user property. So you could achieve it with:
Map<String, User> userMap = new HashMap<String, User>();
userMap.put("user", user);
String json = "";
try {
json = objectMapper.writeValueAsString(userMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
}

Deserializing json with various keys as value

I have json like:
{"avatars": {
"1": "value",
"2":"value",
"900":"value"
}
}
And my model:
class Response{
List<Avatar> avatars;
}
class Avatar{
String id;
String value;
}
How do I properly parse the Json using Jackson
You should use json like this to automaticaly parse:
{"avatars": [
{"id": "1", "value": "someValue1"},
{"id": "2", "value": "someValue2"},
{"id": "300", "value": "someValue300"},
]
}
or write custom parser for Jackson.
Try this:
Using Java JSON library
public class Test {
public static void main(String[] args) {
Response response = new Response();
Serializer.serialize("{\"avatars\": { \"1\": \"value\", \"2\":\"value\", \"900\":\"value\" }}", response);
System.out.println(response.toString());
}
}
class Serializer {
public static void serialize(String j, Response response) {
try {
JSONObject json = new JSONObject(j).getJSONObject("avatars");
Iterator keys = json.keys();
while (keys.hasNext()) {
String id = keys.next().toString();
String value = json.getString(id);
response.addAvatar(id, value);
}
} catch (JSONException ignore) {
}
}
}
/**
* This is a response class
*/
class Response {
List<Avatar> avatars;
public Response() {
/**
* You can use LinkedList, I think it's the best way.
*/
this.avatars = new LinkedList<Avatar>();
}
public void addAvatar(String id, String value) {
this.avatars.add(new Avatar(id, value));
}
public String toString() {
String result = "";
for (Avatar avatar : this.avatars) {
result += (result.length() == 0 ? "" : ", ") + "[" + avatar.getId() + "=" + avatar.getValue() + "]";
}
return result;
}
}
/**
* This is an avatar class
*/
class Avatar {
private String id;
private String value;
public Avatar(String id, String value) {
this.id = id;
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Hope this helps!
You can just use a converter, which avoids the complexity of a full custom deserializer:
#JsonDeserialize(converter = AvatarMapConverter.class)
public List<Avatar> avatars;
The converter needs to declare that it can accept some other type that Jackson can deserialize to, and produce a List<Avatar>. Extending StdConverter will do the plumbing for you:
public class AvatarMapConverter extends StdConverter<Map<String, String>, List<Avatar>> {
#Override
public List<Avatar> convert(Map<String, String> input) {
List<Avatar> output = new ArrayList<>(input.size());
input.forEach((id, value) -> output.add(new Avatar(id, value)));
return output;
}
}
If you need to serialize too, you can write a converter to go the other way and reference that from a #JsonSerialize annotation.

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 !

Categories

Resources