Can anybody say where I am doing wrong. I have json like that
[{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"},{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"},{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"},{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"}]
And I parse to this class.
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
#JsonPropertyOrder({
"shards"
})
public class ShardsResponse extends Response{
#JsonProperty("shards")
private List<Shards> shards = new ArrayList<Shards>();
/**
*
* #return
* The shards
*/
#JsonProperty("shards")
public List<Shards> getShards() {
return shards;
}
/**
*
* #param shards
* The shards
*/
#JsonProperty("shards")
public void setShards(List<Shards> shards) {
this.shards = shards;
}
}
And Shards class is :
/**
*
* #return
* The locales
*/
#JsonProperty("locales")
public List<String> getLocales() {
return locales;
}
/**
*
* #param locales
* The locales
*/
#JsonProperty("locales")
public void setLocales(List<String> locales) {
this.locales = locales;
}
/**
*
* #return
* The name
*/
#JsonProperty("name")
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The hostname
*/
#JsonProperty("hostname")
public String getHostname() {
return hostname;
}
/**
*
* #param hostname
* The hostname
*/
#JsonProperty("hostname")
public void setHostname(String hostname) {
this.hostname = hostname;
}
/**
*
* #return
* The slug
*/
#JsonProperty("slug")
public String getSlug() {
return slug;
}
/**
*
* #param slug
* The slug
*/
#JsonProperty("slug")
public void setSlug(String slug) {
this.slug = slug;
}
}
So I'm using ObjectMapper.readValue(jsontext, responseclass)
JSONObject object = new JSONObject(JsonString);
JsonString = "";
Iterator<String> keys= object.keys();
while (keys.hasNext()){
String keyValue = (String)keys.next();
JsonString= JsonString+ object.getString(keyValue);
}
JsonString= JsonString.substring(1, JsonString.length()-1);
Object response = ObjectMapper.readValue(JsonString, ShardsResponse.class);
At the last I am getting out of START_ARRAY token. Please anybody tell me what's wrong.
Cause I'm trying so much things, but I never find the solution.
How can I fix it.
Your json string is correct, but not for the object you expect, as someone mentioned already, you need to use a List
import java.io.IOException;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public class ParseJson {
private static final String jsonString = "[{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"},{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"},{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"},{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"}]";
public static void parse() {
try {
TypeReference<List<Shards>> typeRef = new TypeReference<List<Shards>>() { };
ObjectMapper mapper = new ObjectMapper();
List<Shards> list = mapper.readValue(jsonString, typeRef);
for ( Shards s : list )
{
s.printDebug();
}
ShardsResponse sr = new ShardsResponse(list);
String srString = mapper.writeValueAsString(sr);
System.out.println("srString: " + srString );
TypeReference<ShardsResponse> typeRef2 = new TypeReference<ShardsResponse>() { };
ShardsResponse sr2 = mapper.readValue(srString, typeRef2);
sr2.printDebug();
} catch ( IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ParseJson.parse();
}
}
Edit:
If you expect a ShardsResponse back, your json string should look like this:
{"shards":[{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"},{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"},{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"},{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"}]}
Easiest way to figure out what the json will look like is to dump it out:
ShardsResponse sr = new ShardsResponse(list);
String srString = mapper.writeValueAsString(sr);
System.out.println("srString: " + srString );
Edit:
Adding additional Classes for clarity:
ShardsResponses.java
import java.util.ArrayList;
import java.util.List;
public class ShardsResponse {
private List<Shards> shards = new ArrayList<Shards>();
public ShardsResponse() { }
public ShardsResponse( List<Shards> shards)
{
this.shards = shards;
}
public List<Shards> getShards() {
return shards;
}
public void setShards(List<Shards> shards) {
this.shards = shards;
}
public void printDebug()
{
for ( Shards s : shards)
{
s.printDebug();
System.out.println("");
}
}
}
Shards.java:
import java.util.List;
public class Shards {
private List<String> locales;
private String name;
private String hostname;
private String slug;
private String region_tag;
public List<String> getLocales() {
return locales;
}
public void setLocales(List<String> locales) {
this.locales = locales;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public void printDebug()
{
System.out.println("name: " + name);
System.out.println("hostname: " + hostname);
System.out.println("slug: " + slug);
System.out.println("region_tag: " + region_tag);
for ( String s : locales )
{
System.out.println("Locals: " + locales);
}
}
public String getRegion_tag() {
return region_tag;
}
public void setRegion_tag(String region_tag) {
this.region_tag = region_tag;
}
}
you have an jsonArray but you are trying to parse a jsonObject. change your method to return a list of objects instead of one object.
Related
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();
}
}
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!
I'm getting a problem with the return value after the post request, the response string contains the requested JSON text but the dataBean is null ??
#Override
public wDataBean doInBackground(Void... params) {
wDataBean dataBean = new wDataBean();
try {
Response response = client.newCall(request).execute();
String responseString = response.body().string();
JSONObject jsonObject = new JSONObject(responseString);
Gson gson = new Gson();
dataBean = gson.fromJson(jsonObject.toString(), wDataBean.class);
}
catch (final IOException e)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
return dataBean;
}
This is a sample of the response:
{ "IsOK":true,
"Response":"Logged in successfully",
"MyArray":{ "user":"35",
"email":"email#domain.com",
"img":"https:\/\/www.mywebsite.com\/uploads\/136_image.png",
"fname":"First Name",
"lname":"Last Name",
"myToken":
{
"auth":"xyzxyzyxyzxyzxyzxyzxyzxyzxyzxyzxyzxyz",
"expiry":"1980-01-01 00:00:00"
}
},
"myToken":{}
}
wDataBean.java
public class wDataBean {
private Main1 main;
public Main1 getMain() {return main;}
public void setMain(Main1 main) {this.main = main;}
class Main1 {
boolean IsOK;
String Response;
JSONArray MyArray;
int user;
String email;
String img;
String fname;
String lname;
JSONArray myToken;
String auth;
Date expiry;
public boolean isOK() {return isOK();}
public int getUser() {return user;}
public JSONArray getMyArray() {return MyArray;}
public String getEmail() {return email;}
public String getImg() {return img;}
public String getResponse() {return Response;}
public Date getExpiry() {return expiry;}
public JSONArray getMyToken() {return myToken;}
public String getAuth() {return auth;}
public String getFname() {return fname;}
public String getLname() {return lname;}
public void setAuth(String auth) {this.auth = auth;}
public void setEmail(String email) {this.email = email;}
public void setExpiry(Date expiry) {this.expiry = expiry;}
public void setFname(String fname) {this.fname = fname;}
public void setImg(String img) {this.img = img;}
public void setLname(String lname) {this.lname = lname;}
public void setMyArray(JSONArray myArray) {MyArray = myArray;}
public void setMyToken(JSONArray myToken) {this.myToken = myToken;}
public void setOK(boolean OK) {IsOK = OK;}
public void setResponse(String response) { Response = response;}
public void setUser(int user) { this.user = user;}
}
}
The goal is to get "auth" and "expiry" from myToken
This should be your bean class -
public class WDataBean {
#SerializedName("IsOK")
#Expose
private Boolean isOK;
#SerializedName("Response")
#Expose
private String response;
#SerializedName("MyArray")
#Expose
private MyArray myArray;
#SerializedName("myToken")
#Expose
private MyToken_ myToken;
/**
*
* #return
* The isOK
*/
public Boolean getIsOK() {
return isOK;
}
/**
*
* #param isOK
* The IsOK
*/
public void setIsOK(Boolean isOK) {
this.isOK = isOK;
}
/**
*
* #return
* The response
*/
public String getResponse() {
return response;
}
/**
*
* #param response
* The Response
*/
public void setResponse(String response) {
this.response = response;
}
/**
*
* #return
* The myArray
*/
public MyArray getMyArray() {
return myArray;
}
/**
*
* #param myArray
* The MyArray
*/
public void setMyArray(MyArray myArray) {
this.myArray = myArray;
}
/**
*
* #return
* The myToken
*/
public MyToken_ getMyToken() {
return myToken;
}
/**
*
* #param myToken
* The myToken
*/
public void setMyToken(MyToken_ myToken) {
this.myToken = myToken;
}
public class MyToken_ {
}
public class MyToken {
#SerializedName("auth")
#Expose
private String auth;
#SerializedName("expiry")
#Expose
private String expiry;
/**
*
* #return
* The auth
*/
public String getAuth() {
return auth;
}
/**
*
* #param auth
* The auth
*/
public void setAuth(String auth) {
this.auth = auth;
}
/**
*
* #return
* The expiry
*/
public String getExpiry() {
return expiry;
}
/**
*
* #param expiry
* The expiry
*/
public void setExpiry(String expiry) {
this.expiry = expiry;
}
}
public class MyArray {
#SerializedName("user")
#Expose
private String user;
#SerializedName("email")
#Expose
private String email;
#SerializedName("img")
#Expose
private String img;
#SerializedName("fname")
#Expose
private String fname;
#SerializedName("lname")
#Expose
private String lname;
#SerializedName("myToken")
#Expose
private MyToken myToken;
/**
*
* #return
* The user
*/
public String getUser() {
return user;
}
/**
*
* #param user
* The user
*/
public void setUser(String user) {
this.user = user;
}
/**
*
* #return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* #param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* #return
* The img
*/
public String getImg() {
return img;
}
/**
*
* #param img
* The img
*/
public void setImg(String img) {
this.img = img;
}
/**
*
* #return
* The fname
*/
public String getFname() {
return fname;
}
/**
*
* #param fname
* The fname
*/
public void setFname(String fname) {
this.fname = fname;
}
/**
*
* #return
* The lname
*/
public String getLname() {
return lname;
}
/**
*
* #param lname
* The lname
*/
public void setLname(String lname) {
this.lname = lname;
}
/**
*
* #return
* The myToken
*/
public MyToken getMyToken() {
return myToken;
}
/**
*
* #param myToken
* The myToken
*/
public void setMyToken(MyToken myToken) {
this.myToken = myToken;
}
}
}
Can you show me the class wDataBean?
But I venture to say that this can solve
Gson gson = new GsonBuilder().setDateFormat("yyyy-mm-dd HH:mm:ss").create();
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
I have been searching in internet for a while to get a API that convert json into tabular format. I don't have any code which I tried. Please direct me if you have any idea about it.
Eg : Json
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656"},{"countryCode":91,"number":"675432"}],"OtherDetails":[{"Active":true}]}
Output can be(with any separated)
rinu|14|91|99862656|true
rinu|14|91|675432|true
I don't want any ready-made stuff, If I get anything similar to this, I can re-write it.
You might need this:
JacksonRead.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonRead {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
Example example = mapper.readValue(new File("d:\\user.json"),
Example.class);
StringBuilder builder = new StringBuilder();
int i = 0;
for (Phone phone : example.getPhone()) {
builder.append(example.getName()).append("|");
builder.append(example.getAge()).append("|");
builder.append(phone.getCountryCode()).append("|")
.append(phone.getNumber()).append("|")
.append(example.getOtherDetails().get(i).getActive())
.append("|");
builder.append("\n");
}
File file = new File("d:\\user.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(builder.toString());
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example.java
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
public class Example {
#JsonProperty("name")
private String name;
#JsonProperty("age")
private String age;
#JsonProperty("Phone")
private List<Phone> Phone = new ArrayList<Phone>();
#JsonProperty("OtherDetails")
private List<OtherDetail> OtherDetails = new ArrayList<OtherDetail>();
/**
*
* #return The name
*/
#JsonProperty("name")
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
/**
*
* #return The age
*/
#JsonProperty("age")
public String getAge() {
return age;
}
/**
*
* #param age
* The age
*/
#JsonProperty("age")
public void setAge(String age) {
this.age = age;
}
/**
*
* #return The Phone
*/
#JsonProperty("Phone")
public List<Phone> getPhone() {
return Phone;
}
/**
*
* #param Phone
* The Phone
*/
#JsonProperty("Phone")
public void setPhone(List<Phone> Phone) {
this.Phone = Phone;
}
/**
*
* #return The OtherDetails
*/
#JsonProperty("OtherDetails")
public List<OtherDetail> getOtherDetails() {
return OtherDetails;
}
/**
*
* #param OtherDetails
* The OtherDetails
*/
#JsonProperty("OtherDetails")
public void setOtherDetails(List<OtherDetail> OtherDetails) {
this.OtherDetails = OtherDetails;
}
#Override
public String toString() {
return "Example [name=" + name + ", age=" + age + ", Phone=" + Phone
+ ", OtherDetails=" + OtherDetails + "]";
}
}
Phone.java
import org.codehaus.jackson.annotate.JsonProperty;
public class Phone {
#JsonProperty("countryCode")
private Integer countryCode;
#JsonProperty("number")
private String number;
/**
*
* #return The countryCode
*/
#JsonProperty("countryCode")
public Integer getCountryCode() {
return countryCode;
}
/**
*
* #param countryCode
* The countryCode
*/
#JsonProperty("countryCode")
public void setCountryCode(Integer countryCode) {
this.countryCode = countryCode;
}
/**
*
* #return The number
*/
#JsonProperty("number")
public String getNumber() {
return number;
}
/**
*
* #param number
* The number
*/
#JsonProperty("number")
public void setNumber(String number) {
this.number = number;
}
#Override
public String toString() {
return "Phone [countryCode=" + countryCode + ", number=" + number + "]";
}
}
OtherDetail.java
import org.codehaus.jackson.annotate.JsonProperty;
public class OtherDetail {
#JsonProperty("Active")
private Boolean Active;
/**
*
* #return The Active
*/
#JsonProperty("Active")
public Boolean getActive() {
return Active;
}
/**
*
* #param Active
* The Active
*/
#JsonProperty("Active")
public void setActive(Boolean Active) {
this.Active = Active;
}
#Override
public String toString() {
return "OtherDetail [Active=" + Active + "]";
}
}
user.json
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656"},{"countryCode":91,"number":"675432"}],"OtherDetails":[{"Active":true}]}
I tried the library json2flat with the json
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656"},{"countryCode":91,"number":"675432"}],"OtherDetails":[{"Active":true}]}
it gives a CSV like ::
rinu|14|91|99862656|
rinu|14|91|675432 |
rinu| | | |true
But if you tweak the json a little bit like ::
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656","Active":true},{"countryCode":91,"number":"675432","Active":true}]}
it gives the csv exactly as you require.
rinu|14|91|99862656|true
rinu|14|91|675432|true
Give it a try. After all the solution depends upon how the user wants to interpret the json.