How do I deserialize my immutable subclass? - java

I'm currently trying to deserialize a json-response. My object uses the builder pattern and the consumer interface.
I'm doing a http-request to an external source and get my response as json. All the responses are strings and look like:
{
"a": "198",
"b": "F",
"c": "30",
"d": "2019-02-01",
"e": "2019-12-31"
}
I've changed the name of my model and my key to Model and Key so there might be typos, sorry for that.
#JsonDeserialize(builder = Model.Builder.class)
public class Model {
private final Data data;
private Model() {
this.data = new Data();
}
/**
* #return key
*/
public Key getKey() {
return data.key;
}
/**
* #return Tax Form
*/
public String getTaxForm() {
return data.taxForm;
}
/**
* #return tax table
*/
public int getTaxTable() {
return data.taxTable;
}
/**
* #return tax percent
*/
public BigDecimal getTaxPercent() {
return data.taxPercent;
}
/**
* #return Valid from
*/
public LocalDate getValidFrom() {
return data.validFrom;
}
/**
* #return Valid to
*/
public LocalDate getValidTo() {
return data.validTo;
}
/**
* #param key key
* #return builder
*/
public static Builder getBuilder(Key key) {
return new Builder(key);
}
/**
* #param model the response
* #return builder
*/
public static Builder getBuilder(Model model) {
return new Builder(model);
}
/**
* builder
*/
public static class Builder {
#JsonDeserialize(as = Model.Data.class)
private final Data data;
#JsonCreator
private Builder(Key key) {
this.data = new Data();
this.data.key = key;
}
private Builder(Model model) {
this(model.data.key);
data.taxForm = model.data.taxForm;
data.taxTable = model.data.taxTable;
data.taxPercent = model.data.taxPercent;
data.validFrom = model.data.validFrom;
data.validTo = model.data.validTo;
}
public Builder with(Consumer<Data> consumer) {
consumer.accept(this.data);
return this;
}
public Model build() {
Model internalModel = new Model();
internalModel.data.key = data.key;
internalModel.data.taxForm = data.taxForm;
internalModel.data.taxTable = data.taxTable;
internalModel.data.taxPercent = data.taxPercent;
internalModel.data.validFrom = data.validFrom;
internalModel.data.validTo = data.validTo;
return internalModel;
}
}
/**
* Data
*/
public static final class Data implements Serializable {
private Key key;
#JsonProperty("b")
public String taxForm;
public int taxTable;
public BigDecimal taxPercent;
public LocalDate validFrom;
public LocalDate validTo;
}
}
public class Key {
private final String personalNumber;
public Key(#JsonProperty("a") String personalNumber) {
this.personalNumber = personalNumber;
}
public String getPersonalNumber() {
return personalNumber;
}
}
Currently I am able to deserialize a, but all the other fields are missed. I tried using #JsonProperty in the Data class but that doesn't work. Any ideas?

Related

How can i set this JSON with dynamic keys in POJO and get data from it in Android JAVA?

I am developing an e-commerce app and I am getting this JSON data from API.
{"status": 0, "data": {"stores": {"test-5": {"name": "Test 5", "locality": {"name": "Some place B", "id": 2}, "cover": "IMAGE-URL-HERE"}, "test-2": {"name": "Test 2", "locality": {"name": "Some place A", "id": 2}, "cover": "IMAGE-URL-HERE"}}}, "action": [["DATA", "stores"]]}
I have created some POJO for this data too
public class PartnerStoreMainPOJO {
#SerializedName("partnerstore")
#Expose
private PartnerStoresPOJO partnerstore;
/**
*
* #return
* The data
*/
public PartnerStoresPOJO getPartnerStore() {
return partnerstore;
}
/**
*
* #param partnerstore
* The data
*/
public void setPartnerStore(PartnerStoresPOJO partnerstore) {
this.partnerstore = partnerstore;
}
}
//-------------
public class PartnerStoresPOJO {
#SerializedName("partnerstoredetail")
#Expose
private Map<String, PartnerStoreDetailPOJO> partnerstoredetail;
/**
*
* #return
* The feeds
*/
public Map<String, PartnerStoreDetailPOJO> getpartnerstoredetail() {
return partnerstoredetail;
}
/**
*
* #param partnerstoredetail
* The feeds
*/
public void setpartnerstoredetail(Map<String, PartnerStoreDetailPOJO> partnerstoredetail) {
this.partnerstoredetail = partnerstoredetail;
}
}
//----------------
public class PartnerStoreDetailPOJO {
#SerializedName("partnerstorelocality")
#Expose
private Map<String, PartnerStoreLocalityPOJO> partnerstorelocality;
#SerializedName("cover")
#Expose
private String cover;
#SerializedName("name")
#Expose
private String name;
/**
* #return The name
*/
public String getName() {
return name;
}
/**
* #param name The name
*/
public void setName(String name) {
this.name = name;
}
/**
* #return The cover
*/
public String getCover() {
return cover;
}
/**
* #param cover The address
*/
public void setCover(String cover) {
this.cover = cover;
}
public Map<String, PartnerStoreLocalityPOJO> getpartnerstorelocality() {
return partnerstorelocality;
}
public void setpartnerstorelocality(Map<String, PartnerStoreLocalityPOJO> partnerstorelocality) {
this.partnerstorelocality = partnerstorelocality;
}
}
//----------------
public class PartnerStoreLocalityPOJO {
#SerializedName("name")
#Expose
private String name;
#SerializedName("id")
#Expose
private String id;
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The id
*/
public String getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(String id) {
this.id = id;
}
}
//---------------
Amd i am using volley library. This is my java code-
public void onResultReceived(String response, String tag_json_obj) {
if (tag_json_obj.equals(LOCALITY_SET)){
try {
JSONObject jsonObject=new JSONObject(response);
String data=jsonObject.getString("data");
} catch (JSONException e) {
Log.d("EXCEPTN",e.toString());
e.printStackTrace();
}
}
}
I am using that data string.
Try it once: Do changes accordingly, It can give you a direction for your query.
public void convertJSON(JSONObject jsonObject) {
try {
JSONObject object = jsonObject.getJSONObject("data");
Iterator<String> iter = object.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = object.get(key);
JSONObject obj2 = object.getJSONObject(key);
//set key to POJO
Iterator<String> iter2 = obj2.keys();
while (iter2.hasNext()) {
String key2 = iter2.next();
//....so on
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Return List within List REST API Jax Rs

I am creating a REST API from java where I am returning an object list as follows:
#Path("/order")
public class OrderService implements IService
{
#Override
public Response get()
{
List<DataObj> list = new ArrayList<>();
List<SubDataObj> subList = new ArrayList<>();
subList.add(new SubDataObj("1"));
GenericEntity<List<DataObj>> entity;
list.add(new DataObj("A", "22", TestEnum.test1, DateTime.now(), subList));
list.add(new DataObj("B", "23", TestEnum.test2, DateTime.now(), subList));
entity = new GenericEntity<List<DataObj>>(list){};
return Response.ok(entity).build();
}
}
Here the service returns the Response fine when not using the subList, which is a object list within the DataObj class. However, when I am using it, i get an error as:
SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<dyno.scheduler.restservice.DataObj>.
Here are the DataObj and the SubDataObj classes:
#XmlRootElement
class DataObj
{
private String name;
private String age;
private TestEnum enumVal;
private DateTime currentDate;
private List<SubDataObj> subData;
public DataObj(String name, String age, TestEnum enumVal, DateTime currentDate, List<SubDataObj> subData)
{
this.name = name;
this.age = age;
this.enumVal = enumVal;
this.currentDate = currentDate;
this.subData = subData;
}
public DataObj() {}
/**
* #return the name
*/
public String getName()
{
return name;
}
/**
* #param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* #return the age
*/
public String getAge()
{
return age;
}
/**
* #param age the age to set
*/
public void setAge(String age)
{
this.age = age;
}
/**
* #return the enumVal
*/
public TestEnum getEnumVal()
{
return enumVal;
}
/**
* #param enumVal the enumVal to set
*/
public void setEnumVal(TestEnum enumVal)
{
this.enumVal = enumVal;
}
/**
* #return the currentDate
*/
public DateTime getCurrentDate()
{
return currentDate;
}
/**
* #param currentDate the currentDate to set
*/
public void setCurrentDate(DateTime currentDate)
{
this.currentDate = currentDate;
}
/**
* #return the subData
*/
public List<SubDataObj> getSubData()
{
return subData;
}
/**
* #param subData the subData to set
*/
public void setSubData(List<SubDataObj> subData)
{
this.subData = subData;
}
}
DataSubObj class:
class SubDataObj
{
private String subId;
public SubDataObj(String subId)
{
this.subId = subId;
}
/**
* #return the subId
*/
public String getSubId()
{
return subId;
}
/**
* #param subId the subId to set
*/
public void setSubId(String subId)
{
this.subId = subId;
}
}
I tried adding #XmlRootElement annotation to my SubDataObj class as well, which didn't work.
Any help would be appreciated!

Deserialize Array Of Objects with the first item being the counter of the elements

Hello i was trying to deserialize the following JSON response from a Web Api:
{
"response": [
370968,
{
"aid": 65843156,
"owner_id": 17519165,
"artist": "Bass Test",
"title": "дурной басс!",
"duration": 238,
"url": "http://cs6-10v4.vk-cdn.net/p22/c412a04df93035.mp3?extra=9YguhLftfZDDwo4JKBVwvlx_V1vwlu5pNU4-WremEqM9bL8eN2vh3_qu7bAg9EgNCj0ztEcMurarC499x8X2MpUaipykG2LDueWe0QQMrIPplkxKdV1xcQp35baDwA84l-luVxai9maX",
"lyrics_id": "6214304"
},
{
"aid": 207425918,
"owner_id": 96085484,
"artist": "► DJ Pleased",
"title": "Bass Test № 04 (New 2013)",
"duration": 328,
"url": "http://cs6-7v4.vk-cdn.net/p23/6d7071221fb912.mp3?extra=O5ih5W5YkaEkXhHQSOKeDzvtr0V8xyS1WhIgjYLROFOMcW__FpU3mSf5udwdEAq6kkcz7QSy5jB57rTgSxnRJXCySZy2b0J_a2DvzFUBqVX6lcKqlarTryP_loQyk-SYPbFLh-9mSzm_iA",
"lyrics_id": "86651563",
"genre": 10
}
]
}
My intention is to build a class to get the items in the response and use them in my Java Android application. The problem is that the first item of the response array is a number and not an object like the next items. So when I parse it with Gson it gives me the error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 20 path $.response[0]
I used the retrofit android library with the following POJO class (witch works if i don't have the counter in the response):
import java.util.HashMap;
import java.util.Map;
public class Response {
private Integer aid;
private Integer ownerId;
private String artist;
private String title;
private Integer duration;
private String url;
private String lyricsId;
private Integer genre;
private String album;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The aid
*/
public Integer getAid() {
return aid;
}
/**
*
* #param aid
* The aid
*/
public void setAid(Integer aid) {
this.aid = aid;
}
/**
*
* #return
* The ownerId
*/
public Integer getOwnerId() {
return ownerId;
}
/**
*
* #param ownerId
* The owner_id
*/
public void setOwnerId(Integer ownerId) {
this.ownerId = ownerId;
}
/**
*
* #return
* The artist
*/
public String getArtist() {
return artist;
}
/**
*
* #param artist
* The artist
*/
public void setArtist(String artist) {
this.artist = artist;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The duration
*/
public Integer getDuration() {
return duration;
}
/**
*
* #param duration
* The duration
*/
public void setDuration(Integer duration) {
this.duration = duration;
}
/**
*
* #return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* #param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* #return
* The lyricsId
*/
public String getLyricsId() {
return lyricsId;
}
/**
*
* #param lyricsId
* The lyrics_id
*/
public void setLyricsId(String lyricsId) {
this.lyricsId = lyricsId;
}
/**
*
* #return
* The genre
*/
public Integer getGenre() {
return genre;
}
/**
*
* #param genre
* The genre
*/
public void setGenre(Integer genre) {
this.genre = genre;
}
/**
*
* #return
* The album
*/
public String getAlbum() {
return album;
}
/**
*
* #param album
* The album
*/
public void setAlbum(String album) {
this.album = album;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
Is there any way to make it work? I don't have access to the API server so i cant change how the result is displayed. To generate the class i used http://www.jsonschema2pojo.org/ but i was able to generate it only by removing the counter from the response.
The wrapper class VKSongApi:
public class VKSongApi {
private List<Response> response = new ArrayList<Response>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The response
*/
public List<Response> getResponse() {
return response;
}
/**
*
* #param response
* The response
*/
public void setResponse(List<Response> response) {
this.response = response;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
The retrofit interface class is:
public interface VKApi {
#GET("/method/audio.search")
Call<VKSongApi> search(#Query("q") String query, #Query("access_token") String token);
}
Then in the MainActivity i do:
public static final String BASE_URL = "https://api.vk.com/method/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
VKApi apiService =
retrofit.create(VKApi.class);
And call the method from the MainActivity with:
Call<VKSongApi> call = apiService.search("test","fff9ef502df4bb10d9bf50dcd62170a24c69e98e4d847d9798d63dacf474b674f9a512b2b3f7e8ebf1d69");
call.enqueue(new Callback<VKSongApi>() {
#Override
public void onResponse(Call<VKSongApi> call, Response<VKSongApi> response) {
int statusCode = response.code();
VKSongApi song = response.body();
Log.d(TAG,response.message());
}
#Override
public void onFailure(Call<VKSongApi> call, Throwable t) {
//Here the error occurs com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 20 path $.response[0]
Log.d(TAG,"Failure");
}
});
I solved by parsing manually the response using a custom deserializer class

Spring Mongodb pagination of nested collection field

I have a collection of document inside another document. Would like to implement pagination on nested element while fetching the data. Could you please let me know how to do that? In the structure I would like to fetch messages using pagination.
public abstract class CommonDomainAttributes implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
#Id
protected String id;
#JsonIgnore
#CreatedDate
protected Date createDate;
//#JsonIgnore
#LastModifiedDate
//#JsonSerialize(using=JsonDateSerializer.class)
protected Date lastModifiedDate;
#JsonIgnore
#CreatedBy
protected String createdBy;
#JsonIgnore
#LastModifiedBy
protected String lastModifiedBy;
/**
* #return the id
*/
public String getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* #return the createDate
*/
public Date getCreateDate() {
return createDate;
}
/**
* #param createDate the createDate to set
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
* #return the lastModifiedDate
*/
public Date getLastModifiedDate() {
return lastModifiedDate;
}
/**
* #param lastModifiedDate the lastModifiedDate to set
*/
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
/**
* #return the createdBy
*/
public String getCreatedBy() {
return createdBy;
}
/**
* #param createdBy the createdBy to set
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* #return the lastModifiedBy
*/
public String getLastModifiedBy() {
return lastModifiedBy;
}
/**
* #param lastModifiedBy the lastModifiedBy to set
*/
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (id == null ? 0 : id.hashCode());
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CommonDomainAttributes other = (CommonDomainAttributes) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CommonDomainAttributes [id=").append(id)
.append(", createDate=").append(createDate)
.append(", lastModifiedDate=").append(lastModifiedDate)
.append(", createdBy=").append(createdBy)
.append(", lastModifiedBy=").append(lastModifiedBy)
.append(", toString()=").append(super.toString()).append("]");
return builder.toString();
}
}
public class Message extends CommonDomainAttributes implements Serializable{
private String fromuserId;
private String fromuserName;
private String toUserId;
private String touserName;
private String message;
/**
* #return the fromuserId
*/
public String getFromuserId() {
return fromuserId;
}
/**
* #param fromuserId the fromuserId to set
*/
public void setFromuserId(String fromuserId) {
this.fromuserId = fromuserId;
}
/**
* #return the fromuserName
*/
public String getFromuserName() {
return fromuserName;
}
/**
* #param fromuserName the fromuserName to set
*/
public void setFromuserName(String fromuserName) {
this.fromuserName = fromuserName;
}
/**
* #return the toUserId
*/
public String getToUserId() {
return toUserId;
}
/**
* #param toUserId the toUserId to set
*/
public void setToUserId(String toUserId) {
this.toUserId = toUserId;
}
/**
* #return the touserName
*/
public String getTouserName() {
return touserName;
}
/**
* #param touserName the touserName to set
*/
public void setTouserName(String touserName) {
this.touserName = touserName;
}
/**
* #return the message
*/
public String getMessage() {
return message;
}
/**
* #param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Message [fromuserId=");
builder.append(fromuserId);
builder.append(", fromuserName=");
builder.append(fromuserName);
builder.append(", toUserId=");
builder.append(toUserId);
builder.append(", touserName=");
builder.append(touserName);
builder.append(", message=");
builder.append(message);
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}
#Document(collection="discussion")
#TypeAlias("discussion")
public class Discussion extends CommonDomainAttributes implements Serializable{
private String discussionTopic;
private List<Message> messages;
/**
* #return the discussionTopic
*/
public String getDiscussionTopic() {
return discussionTopic;
}
/**
* #param discussionTopic the discussionTopic to set
*/
public void setDiscussionTopic(String discussionTopic) {
this.discussionTopic = discussionTopic;
}
/**
* #return the messages
*/
public List<Message> getMessages() {
return messages;
}
/**
* #param messages the messages to set
*/
public void setMessages(List<Message> messages) {
this.messages = messages;
}
/**
* #param messages the messages to set
*/
public void addMessages(Message message) {
if(null == messages){
messages = new LinkedList<>();
}
messages.add(message);
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Discussion [discussionTopic=");
builder.append(discussionTopic);
builder.append(", messages=");
builder.append(messages);
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}
A bit on Mongo Query Language
In MongoDB, the $slice operator controls the number of items of an array that a query returns. The $slice operator can accept values with following syntax:
[toSkip, toLimit]
Where the first value indicates the number of items in the array to skip and the second value indicates the number of items to return. For example, you can use the following query:
db.discussions.find({}, {messages: {$slice: [20, 10]}})
To return 10 messages, after skipping the first 20 messages of that array.
Bring it to Spring Data World
In order to use $slice operator with Spring Data MongoDB, you should use #Query annotation and its fields attribute. For example, if you have a DiscussionRepository, you could write something like:
public interface DiscussionRepository extends MongoRepository<Discussion, String> {
#Query(value = "{}", fields = "{messages: {$slice: [?0, ?1]}}")
List<Discussion> findDiscussions(int skip, int limit);
}
With this arrangement, following method call:
discussionRepository.findDiscussions(20, 10)
Would generate the same result as:
db.discussions.find({}, {messages: {$slice: [20, 10]}})
With a little bit of work, you can turn the Skip/Limit combination to a pagination functionality.

Android GSON POJO optional field parsing

Ok so heres the thing I am working with an api that for one JSON parameter can return two different types. So I can receive from the server either a JSON Object or a String. I'm pretty new to Android development so if someone could explain to me with maybe a code example how I can handle that problem.
Example json responses {video:"ID OF VIDEO"} or {video:{id:"ID OF VIDEO",...extra data}}. I had a look at custom deserialisers but can't find an example that is easy to follow. There must be a simple way of solving my problem. Currently I receive error "Expected string but found BEGIN OBJECT"
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MyNotification {
#SerializedName("_id")
#Expose
private String Id;
#SerializedName("comment")
#Expose
private String comment;
#SerializedName("createdAt")
#Expose
private String createdAt;
#SerializedName("message")
#Expose
private String message;
#SerializedName("read")
#Expose
private Boolean read;
#SerializedName("recipient")
#Expose
private String recipient;
#SerializedName("sender")
#Expose
private User sender;
#SerializedName("type")
#Expose
private String type;
// #SerializedName("video")
// #Expose
// private String video;
/**
*
* #return
* The Id
*/
public String getId() {
return Id;
}
/**
*
* #param Id
* The _id
*/
public void setId(String Id) {
this.Id = Id;
}
/**
*
* #return
* The comment
*/
public String getComment() {
return comment;
}
/**
*
* #param comment
* The comment
*/
public void setComment(String comment) {
this.comment = comment;
}
/**
*
* #return
* The createdAt
*/
public String getCreatedAt() {
return createdAt;
}
/**
*
* #param createdAt
* The createdAt
*/
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
/**
*
* #return
* The message
*/
public String getMessage() {
return message;
}
/**
*
* #param message
* The message
*/
public void setMessage(String message) {
this.message = message;
}
/**
*
* #return
* The read
*/
public Boolean getRead() {
return read;
}
/**
*
* #param read
* The read
*/
public void setRead(Boolean read) {
this.read = read;
}
/**
*
* #return
* The recipient
*/
public String getRecipient() {
return recipient;
}
/**
*
* #param recipient
* The recipient
*/
public void setRecipient(String recipient) {
this.recipient = recipient;
}
/**
*
* #return
* The sender
*/
public User getSender() {
return sender;
}
/**
*
* #param sender
* The sender
*/
public void setSender(User sender) {
this.sender = sender;
}
/**
*
* #return
* The type
*/
public String getType() {
return type;
}
/**
*
* #param type
* The type
*/
public void setType(String type) {
this.type = type;
}
// /**
// *
// * #return
// * The video
// */
// public String getVideo() {
// return video;
// }
//
// /**
// *
// * #param video
// * The video
// */
// public void setVideo(String video) {
// this.video = video;
// }
}
and the part that craps out
Gson gson = new Gson();
String jsonString = String.valueOf(dataset);
Type listType = new TypeToken<List<MyNotification>>(){}.getType();
notficationsList = (List<MyNotification>) gson.fromJson(jsonString, listType);
Sorry it took so long:
Your best bet is to repair the JSON, if you must map it to an Object.
Try cleaning the JSON with this code:
public static String cleanJson(String json) {
int videoPos = json.indexOf("video");
if(videoPos == -1) {
return json; //return, no video here
}
boolean isObject = false;
int objectBegin = -1;
String cleanedJson = json.replaceAll("\\\"", "\\\\");
for(int i = videoPos; i < cleanedJson.length(); i++) {
if(cleanedJson.charAt(i) == '"') {
System.out.println("string");
return json; // its a string anyway
}
if(cleanedJson.charAt(i) == '{') {
//its an object
// i now is the position beginning the object
objectBegin = i;
}
} //replace " with space
if(objectBegin == -1) {// we did not find any { or " it is a string
return json;
}
boolean inString = false;
int objectEnd = -1;
for(int i = objectBegin; i < cleanedJson.length(); i++) {
//looking for the end of the object;
if(cleanedJson.charAt(i) == '"') inString = !inString;
if(cleanedJson.charAt(i) == '}') {
objectEnd = i;
break;
}
}
if(objectEnd != -1) {
String start = json.substring(0,objectBegin);
String videoPart = json.substring(objectBegin, objectEnd+1);
String end = json.substring(objectEnd+1);
// now we want to get the id
String newVideoPart = "";
int idStart = videoPart.indexOf("id");
int idStringStart = -1;
int idStringEnd = -1;
for(int i = idStart; i < videoPart.length(); i++) {
if(videoPart.charAt(i) == '"') {
if(idStringStart == -1) {
idStringStart = i;
} else {
idStringEnd = i;
break;
}
}
}
if(idStringStart != -1 && idStringEnd != -1) {
newVideoPart = videoPart.substring(idStringStart, idStringEnd+1);
}
return start+newVideoPart+end;
}
return json;
}
Works with these two test jsons:
System.out.println(cleanJson("{video:\"1234\"}"));
System.out.println(cleanJson("{video:{id:\"2345\", name=\"test\"}}"));
Try it like this:
notficationsList = (List<MyNotification>) gson.fromJson(cleanJson(jsonString), listType);
Ok so the solution I went with I wrote my own type adapter that gson allow you to use
public class Helper_StringAdapter extends TypeAdapter<String>{
#Override
public String read(com.google.gson.stream.JsonReader in) throws IOException {
if(in.peek() == JsonToken.NULL){
in.nextNull();
return null;
}else if(in.peek() == JsonToken.BEGIN_OBJECT && in.getPath().contains(".video")){
L.e("VIDEO IS AN OBJECT!");
String userId = readAndReturnVideoId(in);
return userId;
}else{
return in.nextString();
}
}
private String readAndReturnVideoId(com.google.gson.stream.JsonReader reader) throws IOException{
String id = "";
reader.beginObject();
while(reader.hasNext()){
String name = reader.nextName();
if(name.equals("_id")){
id = reader.nextString();
}else{
reader.skipValue();
}
}
reader.endObject();
L.e("READ ID RETURNED"+id);
return id;
}
#Override
public void write(com.google.gson.stream.JsonWriter out, String value) throws IOException {
L.e("TEST "+out);
}
}
Then in my activity data manager (Recyclerview Adapter)
public void updateData (JSONArray dataset) {
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(String.class,new Helper_StringAdapter());
Gson gson = gsonb.create();
String jsonString = String.valueOf(dataset);
Type listType = new TypeToken<List<FrameNotification>>(){}.getType();
notficationsList = (List<FrameNotification>) gson.fromJson(jsonString, listType);
}
Seems to do the job

Categories

Resources