How to Parse json array without any key value using objectMapper? - android

I am getting json response string like this.
[
"assets\/imgs\/choicelogos\/choice-logo.jpg",
"assets\/imgs\/choicelogos\/family-health-logo.jpg",
"assets\/imgs\/choicelogos\/four-corners-logo.jpg",
"assets\/imgs\/choicelogos\/grady-logo.jpg",
"assets\/imgs\/choicelogos\/hands-logo.jpg",
"assets\/imgs\/choicelogos\/morehouse-logo.jpg",
"assets\/imgs\/choicelogos\/smc-logo.jpg"
]
And this is my approach to parse this string using ObjectMapper class.
public String parseResponse(String strResponseString) {
if (MBUtil.isEmpty(strResponseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<WebAPIResponse> someClassList = objectMapper.readValue(strResponseString, typeFactory.constructCollectionType(List.class, WebAPIResponse.class));
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}
But I am not able to parse. It is throwing errorMsg = null. Please any one help what I need to change?

Here is the solution of this question.
#JsonIgnoreProperties(ignoreUnknown = true)
private List<String> mWebAPIResponse;
#Override
public String parseResponse(String strResponseString) {
if (MBUtil.isEmpty(strResponseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
List<String> webAPIResponse = objectMapper.readValue(strResponseString, new TypeReference<ArrayList<String>>() {});
this.mWebAPIResponse = webAPIResponse;
} catch (Exception e) {
e.printStackTrace();
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}

Related

org.json.JSON.typeMismatch(JSON.java:111)

I am getting a org.json.JSON.typeMismatch(JSON.java:111) error while trying to create a JSON array. The received data looks like this:
{
"result":[
{
"#type":"d",
"#rid":"#-2:0",
"#version":0,
"a_adres":"kepez merkez geliyor herkez",
"takipkodu":"464664",
"agirlik":50
},
{
"#type":"d",
"#rid":"#-2:1",
"#version":0,
"a_adres":"merkez mahallesi 4 sok",
"takipkodu":"sd4fs654f64",
"agirlik":60
}
]
}
Code:
protected String doInBackground(String... urls) {
try {
String getResponse = get("http://178.18.206.128:2480/command/nakliye/sql/select a_adres,takipkodu,agirlik from yukilan");
return getResponse;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String getResponse) {
ListView liste=(ListView)findViewById(R.id.list_view);
try {
JSONArray yukilanarray = new JSONArray(getResponse);
List<Yukilan> yukilanlar = new ArrayList<>();
//Populate the EmployeeDetails list from response
for (int i = 0; i<yukilanarray.length();i++){
Yukilan yeniilan = new Yukilan();
JSONObject yukilanobject = yukilanarray.getJSONObject(i);
yeniilan.setAdres(yukilanobject.getString(KEY_ADRES));
yeniilan.setAgirlik(yukilanobject.getString(KEY_AGIRLIK));
yeniilan.setTakip_kod(yukilanobject.getString(KEY_TAKIPKODU));
yukilanlar.add(yeniilan);
}
//Create an adapter with the EmployeeDetails List and set it to the LstView
yukilanadapter = new Yukilanadapter(yukilanlar,getApplicationContext());
liste.setAdapter(yukilanadapter);
} catch (JSONException e) {
e.printStackTrace();
}
// System.out.println(getResponse);
}
Please help.
I think you made a mistake in reading the json. the first element would be a JSONObject not a JSONArray.Below is the revised code.
protected String doInBackground(String... urls) {
try {
String getResponse = get("http://178.18.206.128:2480/command/nakliye/sql/select a_adres,takipkodu,agirlik from yukilan");
return getResponse;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String getResponse) {
ListView liste=(ListView)findViewById(R.id.list_view);
try {
JSONObject jsonObject = new JSONObject(getResponse);
JSONArray yukilanarray = jsonObject.getJSONArray("result");
List<Yukilan> yukilanlar = new ArrayList<>();
//Populate the EmployeeDetails list from response
for (int i = 0; i<yukilanarray.length();i++){
Yukilan yeniilan = new Yukilan();
JSONObject yukilanobject = yukilanarray.getJSONObject(i);
yeniilan.setAdres(yukilanobject.getString(KEY_ADRES));
yeniilan.setAgirlik(yukilanobject.getString(KEY_AGIRLIK));
yeniilan.setTakip_kod(yukilanobject.getString(KEY_TAKIPKODU));
yukilanlar.add(yeniilan);
}
//Create an adapter with the EmployeeDetails List and set it to the LstView
yukilanadapter = new Yukilanadapter(yukilanlar,getApplicationContext());
liste.setAdapter(yukilanadapter);
} catch (JSONException e) {
e.printStackTrace();
}
// System.out.println(getResponse);
}

SignalR for Android: how can I pass dynamic class to SubscriptionHandler1

I have a method startSignalR calling
mHub.on("broadcastMessage",
new SubscriptionHandler1<CustomMessage>() {
#Override
public void run(final CustomMessage msg) {
final String finalMsg = msg.UserName + ": " + msg.Message;
System.out.println(finalMsg);
}
}
, CustomMessage.class);
Now I wanna a dynamic class (not only CustomMessage) passed to the method, I have used Class <T> tClass as parameter of "startSignalR", but get error at
new SubscriptionHandler1<tClass>()
Would you please tell me how to solve this?
I have found a solution
public <T> void startSignalR(String transport, String serverUrl, final String userName, final Class<T> tClass) {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
Credentials credentials = new Credentials() {
#Override
public void prepareRequest(Request request) {
request.addHeader(HEADER_KEY_USERNAME, userName);
}
};
mConnection = new HubConnection(serverUrl);
mConnection.setCredentials(credentials);
mHub = mConnection.createHubProxy(SERVER_HUB_CHAT);
if (transport.equals("ServerSentEvents")) {
mTransport = new ServerSentEventsTransport(mConnection.getLogger());
} else if (transport.equals("LongPolling")) {
mTransport = new LongPollingTransport(mConnection.getLogger());
}
mAwaitConnection = mConnection.start(mTransport);
try {
mAwaitConnection.get();
} catch (InterruptedException e) {
e.printStackTrace();
return;
} catch (ExecutionException e) {
e.printStackTrace();
return;
}
mHub.on("broadcastMessage",
new SubscriptionHandler1<Object>() {
#Override
public void run(final Object msg) {
final String finalMsg;
Gson gson = new Gson();
Object object = gson.fromJson(msg.toString(), tClass);
Field[] fields = object.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
try {
System.out.println("Value = " + fields[i].get(object));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
, Object.class);
...
}

how to convert my java object to json and save it in sd card

I don't know how to do after this to convert my Java to JSON with Jackson
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectMapper mapper = new ObjectMapper();
Book b = new Book();
ArrayList<Book> listBook = new ArrayList<Book>();
listBook.add(b);
b = new Book();
b.setName("exam");
b.setFileName("res/raw/exam.txt");
b.setCate(0); //4 categories here
b.setSoundFileName("res/raw/exams.mp3");
b.setTranFileName("res/raw/examt.txt");
listBook.add(b);
b = new Book();
b.setName("test");
b.setCate(0);
b.setFileName("res/raw/test.txt");
b.setSoundFileName("res/raw/tests.mp3")
b.setTranFileName("res/raw/textt.txt");
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(listBook);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("ttt", "show ans : "+jsonString);
How do I do next to write this to my SD card?
as user Zain has told, Gson is more convenient to use, However, assuming that you are getting the Json string from this line:
jsonString = mapper.writeValueAsString(listBook);
Then use this method to write the string to a file in sdcard.
public static void writeStringToFile(String p_string, String p_fileName)
{
FileOutputStream m_stream = null;
try
{
m_stream = new FileOutputStream(p_fileName);
m_stream.write(p_string.getBytes());
m_stream.flush();
}
catch (Throwable m_th)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_th);
}
finally
{
if (m_stream != null)
{
try
{
m_stream.close();
}
catch (Throwable m_e)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_e);
}
m_stream = null;
}
}
}

Gson - Convert from Json to List<>

i'm having an issue converting Json to List<>, I have tried different solutions but no clue
My json result looks like :
{
"Return":0,
"List":[
{
"Code":524288,
"Label":"TEST"
},
{
"Code":524289,
"Label":"TEST1"
},
{
"Code":524290,
"Label":"TEST2"
}
]
}
My code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Questionaire> qstlist = new ArrayList<Questionaire>();
try {
result = new RequestTask().execute("http:/dd.com/categories/current?owner=ccc").get();
json = new JSONObject(result);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
Type listType = new TypeToken<List<Questionaire>>(){}.getType();
qstlist = (List<Questionaire>) gson.fromJson(result, listType);
Questionaire qst = null;
qst = gson.fromJson(result, Questionaire.class);
Toast.makeText(MainActivity.this, "Result "+qstlist.size(), Toast.LENGTH_SHORT).show();
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
My questionnaire class :
public class Questionaire {
String Code;
String Label;
public String getCode() {
return Code;
}
public void setCode(String Code) {
this.Code = Code;
}
public String getLabel() {
return Label;
}
public void setLabel(String Label) {
this.Label = Label;
}
}
Here is everything I can't see what's wrong about that
In this JSON, you get a list of {Code, Label} objects, but in the List property of an object.
You first need to encapsulate this list in an other object.
As in:
public class QuestionaireList {
public List<Questionaire> List;
}
List<Questionaire> qsts = gson.fromJson(result, QuestionaireList.class).List;
You need another class that maps the full result
public class MyJson {
#SerializedName("List")
private List<Questionaire> list;
#SerializedName("Return")
private Integer return1;
//... getters and setters
}
Your type then needs to bind to "MyJson" or whatever you name the class.
I'm assuming it's the List part you want to map to 'qstList'. If so then you need to extract it from the rest of the json first:
Gson gson = new Gson();
JsonObject resultObj = gson.fromJson(result, JsonObject.class);
JsonArray jsonList = resultObj.get("List").getAsJsonArray();
Type listType = new TypeToken<List<Questionaire>>(){}.getType();
qstList = gson.fromJson(jsonList, listType);

How to parse json using jackson android

I am making one webservice application in this I am getting json response and I am parsing that json and I am showing that result in listview.Right now I want to parse with jackson library.I tried some far but I am not getting anything.
code:
private static class Holder
{
ArrayList<UpcomingPojo> holderlist;
}
ObjectMapper objmapper=new ObjectMapper();
Holder holderPojo =objmapper.readValue(jsonResponse,Holder.class);
UpcomingPojo contact = holderPojo.holderlist.get(0);
String name=contact.getName();
pojo:
#JsonIgnoreProperties(ignoreUnknown=true)
public class UpcomingPojo {
String no,name,desc;
public String getNo() {
return no;
}
public String getName() {
return name;
}
}
json:
[
{
"no":"12000",
"name":"ram"
},
{
"no":"12532",
"name":"ravi"
}
]
This is the code for parsing JSON using jackson library.
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient
.execute(new HttpGet(url));
InputStream is = response.getEntity().getContent();
JsonFactory factory = new JsonFactory();
JsonParser jsonParser = factory.createJsonParser(is);
JsonToken token = jsonParser.nextToken();
if (token == JsonToken.START_ARRAY) {
while (token != JsonToken.END_ARRAY) {
token = jsonParser.nextToken();
if (token == JsonToken.START_OBJECT) {
while (token != JsonToken.END_OBJECT) {
token = jsonParser.nextToken();
if (token == JsonToken.FIELD_NAME) {
String objectName = jsonParser
.getCurrentName();
jsonParser.nextToken();
if (0 == objectName
.compareToIgnoreCase("no")) {
Log.d("","no="+jsonParser.getText());
} else if (0 == objectName
.compareToIgnoreCase("name")) {
Log.d("","name="+jsonParser.getText());
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "exception2");
}

Categories

Resources