Send JSon object without 'root' - java

Using Java RestEasy JSon API,
in the next WebService Client code I want to ask you if it is possible to send de JSon object this way:
{
"title" : "Some title book",
"author" : "Some author",
"price" : 99.9
}
... instead of this:
{
"book" :
{
"title" : "Some title book",
"author" : "Some author",
"price" : 99.9
}
}
I mean I dont want to send the 'root' element "book".
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "book")
#XmlType(propOrder = {"title", "author", "price"})
public class Book {
private String title;
private String author;
private Double price;
public Book() {
super();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import com.fasterxml.jackson.databind.ObjectMapper;
public class BookClient {
public static void main(String[] args) {
Response httpResponse = null;
try {
String url = "http://someserver/somepath/etc";
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(url);
Book libro1 = new Book();
libro1.setAuthor("Some author");
libro1.setPrice(99.9);
libro1.setTitle("Some title book");
String jsonEnviado = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(libro1);
Entity<Book> entidad = Entity.entity(libro1, "application/json");
httpResponse = target.request().post(entidad);
Respuesta respuesta = httpResponse.readEntity(Respuesta.class);
if (respuesta != null) {
String jsonRecibido = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(respuesta);
}
int status = httpResponse.getStatus();
if (status == 200) {
logTexto = "OK. Status: " + status;
System.out.println(logTexto);
} else {
logTexto = "KO. Status: " + status;
throw new Exception(logTexto);
}
} catch(Exception e) {
System.out.println("EXCEPTION! " + e.getMessage());
e.printStackTrace();
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (Exception e) {
//IGNORE IT
}
}
}
}
}
Thanks!

Finally I use this to avoid sending root element 'book':
//Entity<Book> entidad = Entity.entity(libro1, "application/json");
//httpResponse = target.request().post(entidad);
Entity<String> entidad = Entity.entity(jsonEnviado, "application/json");
httpResponse = target.request().post(entidad);

Related

Xstream and Inheritance

I have a .dat file that contains some type of products. I'm reading the .dat file and then writing it as JSON and XML files. I'll explain the bug in pic after the files. Here's the problem, in XML file, there's no productCode while in JSON there is. I don't know what's wrong with productCode in XML since I'm passing super(productCode) in both products.
What's wrong with this code?
public static void xmlConverter(List<Product> products) {
XStream xstream = new XStream();
File xmlOutput = new File("data/Products.xml");
PrintWriter xmlPrintWriter = null;
try {
xmlPrintWriter = new PrintWriter(xmlOutput);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
xmlPrintWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n <products>");
xstream.alias("product", Product.class);
xstream.alias("refreshment", Refreshment.class);
xstream.alias("parkingpass", ParkingPass.class);
for (Product aProduct: products) {
String productOutput = xstream.toXML(aProduct);
xmlPrintWriter.write( "\n" + productOutput);
}
xmlPrintWriter.write("\n");
xmlPrintWriter.write("</products>");
xmlPrintWriter.close();
}
Products.dat
6
ff23;R;Labatt Beer-20oz;4.99
90fa;P;25.00
3289;P;55.00
32f4;R;Caramel Popcorn;5.50
90fb;P;20.00
yp23;R;Double Cheeseburger;9.00
Product.java
package Products;
public abstract class Product {
private String productCode;
public Product(String productCode) {
super();
this.productCode = productCode;
}
public String getProductCode() {
return this.productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public abstract String getType();
}
ParkingPass.java
package Products;
public class ParkingPass extends Product {
private double cost;
public ParkingPass(String productCode, double cost) {
super(productCode);
this.cost = cost;
}
public double getParkingFee() {
return cost;
}
public void setParkingFee(double cost) {
this.cost = cost;
}
#Override
public String getType() {
return "P";
}
}
DataConverter.java
import java.io.*;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.thoughtworks.xstream.XStream;
import Products.ParkingPass;
import Products.Product;
import Products.Refreshment;
public class DataConverter {
public static List<Product> readProduct() {
List<Product> productList = new ArrayList<Product>();
Scanner scnr = null;
try {
scnr = new Scanner(new File("data/Products.dat"));
scnr.nextLine();
Product p = null;
while (scnr.hasNext()) {
String line = scnr.nextLine();
String data[] = line.split(";");
String productCode = data[0];
String productType = data[1];
String name = null;
double cost = 0.0;
double parkingFee = 0.0;
if (data.length == 4) {
name = data[2];
cost = Double.parseDouble(data[3]);
} else if (data.length == 3) {
parkingFee = Double.parseDouble(data[2]);
}
if (productType.equals("R")) {
p = new Refreshment(productCode, name, cost);
} else if (productType.equals("P")) {
p = new ParkingPass(productCode, parkingFee);
}
productList.add(p);
}
scnr.close();
return productList;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static void jsonConverter(List<Product> products) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
File jsonOutput = new File("data/Products.json");
PrintWriter jsonPrintWriter = null;
try {
jsonPrintWriter = new PrintWriter(jsonOutput);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (Product aProduct : products) {
String productOutput = gson.toJson(aProduct);
jsonPrintWriter.write(productOutput + "\n");
}
jsonPrintWriter.close();
}
public static void xmlConverter(List<Product> products) {
XStream xstream = new XStream();
File xmlOutput = new File("data/Products.xml");
PrintWriter xmlPrintWriter = null;
try {
xmlPrintWriter = new PrintWriter(xmlOutput);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
xmlPrintWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n <products>");
xstream.alias("product", Product.class);
xstream.alias("refreshment", Refreshment.class);
xstream.alias("parkingpass", ParkingPass.class);
for (Product aProduct: products) {
String productOutput = xstream.toXML(aProduct);
xmlPrintWriter.write( "\n" + productOutput);
}
xmlPrintWriter.write("\n");
xmlPrintWriter.write("</products>");
xmlPrintWriter.close();
}
public static void main(String[] args) {
List<Product> productList = readProduct();
jsonConverter(productList);
xmlConverter(productList);
}
}
}
XML outputs
JSON outputs

Parsing Json Data from Url- Null Values Return - Java

I am using Eclipse IDE to parse the Json data from URl but everty time i run this code it returns null values.
This is the json data from URL
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
This is the POJO class
package com.beto.test.json;
public class Data {
private String id;
private String body;
private String title;
private String userId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Override
public String toString() {
return "ClassPojo [id = " + id + ", body = " + body + ", title = " + title + ", userId = " + userId + "]";
}
}
JsonParserUrl.java class
package com.beto.test.json;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Objects;
/**
* Created by BeytullahC on 23.03.2015.
*/
public class JsonParserFromUrl {
public static void main(String[] args) {
DefaultHttpClient httpClient = null;
try {
httpClient = new DefaultHttpClient();
HttpResponse response = getResponse("http://jsonplaceholder.typicode.com/posts", httpClient);
String outPut = readData(response);
System.out.println(outPut);
Gson gson = new Gson();
List<Data> fromJson = gson.fromJson(outPut, new TypeToken<List<Data>>(){}.getType());
System.out.println("DATA SIZE : "+fromJson.size());
System.out.println("GET FIRST DATA : "+fromJson.get(0));
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
public static HttpResponse getResponse(String url, DefaultHttpClient httpClient) throws IOException {
try {
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(httpGet);
return response;
} catch (IOException e) {
throw e;
}
}
public static String readData(HttpResponse response) throws Exception {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
StringBuffer data = new StringBuffer();
char[] dataLength = new char[1024];
int read;
while (((read = reader.read(dataLength)) != -1)) {
data.append(dataLength, 0, read);
}
return data.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
TestRunner.java class
package com.beto.test.json;
public class TestRunner {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Data data = JsonParserfromUrl.getData("http://jsonplaceholder.typicode.com/posts/1");
System.out.println("result:\n" +data);
}
catch(Exception e)
{
System.out.println("error");
}
}}
Liberaries Added :
- gson-2.3.1.jar
- httpclient-4.5.jar
- commons-logging-1.1.1.jar
- httpclient-cache-4.4.jar
- httpmime-4.0.jar
- commons-codec-1.1.jar
- httpcore-4.4.jar
OUTPUT
ClassPojo [id = " null ", body = " null ", title = " null ", userId ="null"]
Please solve this problem , it should not return null values.
First you should get the JSON String and then parse it to the Data class.
String yourJsonString = readUrl("http://jsonplaceholder.typicode.com/posts/1");
Gson gson = new Gson();
Data data = gson.fromJson(yourJsonString, Data.class);

How do I get the parsed data using GSON

So I was following this tutorial and it has this method.
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... voids) {
Reader reader=API.getData("http://beta.json-generator.com/api/json/get/DiIRBM4");
Type listType = new TypeToken<ArrayList<DoctorBean>>(){}.getType();
beanPostArrayList = new GsonBuilder().create().fromJson(reader, listType);
postList=new StringBuffer();
for(DoctorBean post: beanPostArrayList){
postList.append("\n heroName: "+post.getHeroName()+"\n realName: "+post.getRealName()+"\n\n");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.d("JSON Result ", postList.toString());
}
}.execute();
The Log Result would only show these values.
JSON Result:
heroName: null realName: null
heroName: null realName: null
heroName: null realName: null
This is my JSON data
[
{
"heroName": "Dr. Strange",
"realName": "Stephen Strange"
},
{
"heroName": "Spider-Man",
"realName": "Peter Paker"
},
{
"heroName": "Captain America",
"realName": "Stever Rogers"
}
]
This is my Data Model
import com.google.gson.annotations.SerializedName;
public class DoctorBean {
#SerializedName("heroName")
private String heroName;
#SerializedName("realName")
private String realName;
public DoctorBean(String heroName, String realName) {
this.heroName = heroName;
this.realName = realName;
}
public String getHeroName() {
return heroName;
}
public void setHeroName(String heroName) {
this.heroName = heroName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
And this is my API class
public class API {
private static Reader reader=null;
public static Reader getData(String SERVER_URL) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
reader = new InputStreamReader(content);
} else {
// Log.e("error:", "Server responded with status code: "+ statusLine.getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reader;
}
}
I noticed that the log Result showed 3 rows, so I was thinking it was able to get the length of the array correctly. But as for the data, all was null.
As per your given tutorial,from this link response is as below:
[
{
"date":"11/8/2014",
"auther":"nirav kalola",
"description":"json object parsing using gson library is easy",
"post_name":"json object parsing"
},
{
"date":"12/8/2014",
"auther":"nirav kalola",
"description":"json array parsing using gson library",
"post_name":"json array parsing"
},
{
"date":"17/8/2014",
"auther":"nirav kalola",
"description":"store json file in assets folder and get data when required",
"post_name":"json parsing from assets folder"
}
]
So you need to try below POJO class for GSONBuilder. Replace your name with BeanPost.
import com.google.gson.annotations.SerializedName;
public class BeanPost {
#SerializedName("post_name")
private String post_name;
#SerializedName("auther")
private String auther;
#SerializedName("date")
private String date;
#SerializedName("description")
private String description;
public BeanPost(String post_name, String auther, String date, String description) {
this.post_name = post_name;
this.auther = auther;
this.date = date;
this.description = description;
}
public String getPost_name() {
return post_name;
}
public void setPost_name(String post_name) {
this.post_name = post_name;
}
public String getAuther() {
return auther;
}
public void setAuther(String auther) {
this.auther = auther;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Try to create beanPostArrayList as above pojo class arraylist. And try your code and get appropriate fields from it.
I hope its helps you.
Try this.
Create an array from response :
DoctorBean[] doctorBeanArray = new Gson().fromJson(response, DoctorBean[].class); // Where response is your string response
Then create an ArrayList :
ArrayList<DoctorBean> doctorBeanList = new ArrayList<DoctorBean>(Arrays.asList(doctorBeanArray));

Java: Loading and Displaying XML

I am trying to write a java program that reads in an XML file and returns various elements of interest to the user. I am having some issues getting it to compile and I have created a test class in order for it to be displayed properly. This is what I have thus far.
EDIT: The Bolded Line in the test class is giving me problems. The error is cannot convert from String to Resources.
public class T_Resources {
public static void main(String[] args) {
Resources resources = ResourceImporter.importResourcesFromXML("http://free1.ed.gov/xml/gemexport.xml");
displayResources(resources);
}
private static void displayResources(Resources resources) {
Subject[] subjects;
**Resources resource = resources.getTitle();**
System.out.println(resource.getTitle());
System.out.println(resource.getDescription());
System.out.println(resource.getIdentifier());
subjects = resource.getSubjects();
for (int i=0; i < subjects.length; ++i) {
System.out.println(subjects[i].getCategory() + " :: " + subjects[i].getSubcategory());
}
System.out.println();
}
}
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ResourceImporter {
// This operation loads the XML document specified by the document location, which can a file or a URL,
// and returns a reference to the document. If the operation cannot successfully load the document
// the operation returns the null reference.
//
private static Document loadXMLDocument(String documentLocation) {
// The XML document.
//
Document documentIn = null;
// The parser that reads in an XML files.
//
DocumentBuilder parser = null;
// Pull the document
//
try {
// Obtain a document parser.
//
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
parser = builderFactory.newDocumentBuilder();
documentIn = parser.parse(documentLocation);
} catch (ParserConfigurationException p) {
System.out.println("Error creating parser.");
System.out.println(" " + p.getMessage());
} catch (SAXException s) {
System.out.println("Document is not well formed.");
System.out.println(" " + s.getMessage());
} catch (IOException i) {
System.out.println("Error accessing the file.");
System.out.println(" " + i.getMessage());
} catch (Exception e) {
System.out.println("Unknown error occurred.");
System.out.println(" " + e.getMessage());
}
return documentIn;
}
public static Resources importResourcesFromXML(String documentLocation) {
Resources resource = new Resources();
Document doc;
Element resourceElement;
Element titleElement;
String title;
Element descriptionElement;
String description;
Element identifierElement;
String identifiers;
Element urlElement;
String url;
NodeList subjectList;
Element subjectElement;
String subjects;
Element categoryElement;
String category;
Element subcategoryElement;
String subcategory;
doc = loadXMLDocument(documentLocation);
resourceElement = (Element)doc.getElementsByTagName("resource").item(0);
if (resourceElement != null) {
titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);
resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );
descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);
resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );
identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);
if (identifierElement != null) {
Identifier identifier = new Identifier();
urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);
identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );
subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);
if (subjectElement != null) {
subjectList = subjectElement.getElementsByTagName("subject");
for (int i=0; i < subjectList.getLength(); ++i) {
Subject subject = new Subject();
subjectElement = (Element)subjectList.item(i);
categoryElement = (Element)subjectElement.getElementsByTagName("category").item(0);
subject.setCategory( categoryElement == null ? "unknown" : categoryElement.getTextContent() );
subcategoryElement = (Element)subjectElement.getElementsByTagName("subcategory").item(0);
subject.setSubcategory( subcategoryElement == null ? "unknown" :subcategoryElement.getTextContent() );
resource.addSubject(subject);
}
}
}
}
return resource;
}
}
public class Resources {
private static final int MAX_SUBJECTS = 20;
private String title;
private String description;
private Identifier identifier;
private Subject[] subjects;
private int subjectCount;
public Resources() {
title = "unknown title";
description = "unknown description";
identifier = null;
subjects = new Subject[MAX_SUBJECTS];
subjectCount = 0;
}
public void setTitle(String newTitle) {
title = newTitle;
}
public String getTitle() {
return title;
}
public void setDescription(String newDescription) {
description = newDescription;
}
public String getDescription() {
return description;
}
public void setIdentifier(Identifier newIdentifier) {
identifier = newIdentifier;
}
public Identifier getIdentifier() {
return identifier;
}
public void addSubject(Subject newSubject) {
subjects[subjectCount++] = newSubject;
}
public Subject[] getSubjects() {
Subject[] result = new Subject[subjectCount];
System.arraycopy(subjects, 0, result, 0, subjectCount);
return result;
}
}
public class Subject {
private String category;
private String subcategory;
public Subject() {
String category = "unknown";
String subcategory = "unknown";
}
public Subject(Subject subject) {
category = subject.category;
subcategory = subject.subcategory;
}
public void setCategory(String newCategory) {
category = (newCategory == null) ? "unknown" : newCategory;
}
public String getCategory() {
return category;
}
public void setSubcategory(String newSubcategory) {
subcategory = newSubcategory;
}
public String getSubcategory() {
return subcategory;
}
}
public class Identifier {
private String url;
public Identifier() {
url = "unknown";
}
public void setURL(String newURL) {
url = newURL;
}
public String getURL() {
return url;
}
}
The error lies in here:
private static void displayResources(Resources resources) {
Subject[] subjects;
// DELETE THIS
// **Resources resource = resources.getTitle();**
// RENAME 'resource' to 'resources', or just change the method parameter above...
System.out.println(resources.getTitle());
//System.out.println(resource.getTitle());
System.out.println(resources.getDescription());
//System.out.println(resource.getDescription());
System.out.println(resources.getIdentifier());
//System.out.println(resource.getIdentifier());
....
You pass a Resources Object, and normally you would want to work directly with it?
Currently this just seems borked here, all the other code works, I tested and get fancy console outputs.
EDIT: (Answering a comment below this post.)
In ResourceImporter.java add line following the comment below:
if (resourceElement != null) {
titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);
resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );
descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);
resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );
identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);
if (identifierElement != null) {
Identifier identifier = new Identifier();
urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);
identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );
// ADDED THIS LINE HERE
resource.setIdentifier(identifier);
subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);
if (subjectElement != null) {
subjectList = subjectElement.getElementsByTagName("subject");
....
You may also want to use this line for your syso's in the helper method being used in the main method: System.out.println(resources.getIdentifier().getURL());, otherwise you will get uninterpretable information.
I'd change
private static void displayResources(Resources resources)
to
private static void displayResources(Resources resource)
(notice I removed the 's'), and remove your bold line.
As stated by JB Nizet, your method returns a String when you want the Resources that is passed to your static method.
The getTitle() method is declared as
public String getTitle()
But you're assigning its result to a variabe of type Resources:
Resources resource = resources.getTitle();
That obviously can't work, hence the error, which is quite self-explanatory:
cannot convert from String to Resources
You probably want
String title = resources.getTitle();
instead.

Android : getting multiple data in listview from server in another screen using Json

I am trying to get the jsonobject into next screen listview. I can get 1 values in listview but i have multiple values to be get fetched. How can I do.
here is my code for getting string from server :-
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Get_Friend_List", holder
.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
StringEntity se = new StringEntity(holder.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
resp = response.toString();
String t = EntityUtils.toString(response.getEntity());
try {
JSONArray get_string1 = new JSONArray(t);
JSONObject get_string = null;
// Receive the JSON object from server
String userid = (String) get_string.get("UserId");
String totalusers = (String) get_string.get("TotalUsers");
String SessionID = (String) get_string.get("SessionID");
for (int i = 0; i < get_string1.length(); i++) {
get_string = get_string1.getJSONObject(i);
JSONObject contact = (JSONObject) get_string
.get("contacts-" + i);
String contact_id = (String) contact.get("UserId");
contact_username = (String) contact.get("UserName");
contact_status = (String) contact.get("Status");
Contacts.setStatus(contact_status, i);
Contacts.setUserName(contact_username, i);
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("--error--" + e.getMessage());
}
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}
here is the response from server which I am getting. but storing only last value in listview.
Response from Server----{
"UserId": "1",
"TotalUsers": "4",
"contacts-0": {
"UserId": "3",
"UserName": "kumar",
"Status": "1"
},
"contacts-1": {
"UserId": "2",
"UserName": "rahul",
"Status": "1"
},
"contacts-2": {
"UserId": "4",
"UserName": "vlk",
"Status": "1"
},
"contacts-3": {
"UserId": "5",
"UserName": "vlk",
"Status": "1"
},
"SessionID": "39355"
}
contacts.java
public class Contacts {
public static String[] status = new String[100];
public static String[] usrname = new String[100];
public static String getStatus(int i) {
return status[i];
}
public static String getUserName(int i) {
return usrname[i];
}
public static void setStatus(String status, int i) {
Contacts.status[i] = status;
}
public static void setUserName(String username, int i) {
Contacts.usrname[i] = username;
}
}
The json String has no array type. You need to call the has() method (to test a json attribute is present or not) before you read contacts object. Another issue is in Contacts type. You should have to define the Contact type and initialize List<Contact> to store one or more contacts.
Have a look at the Contact class
public class Contact
{
private String userId;
private String userName;
private String status;
public Contact() {
userId="";
userName="";
status="";
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Override
public String toString() {
return "Contact{" + "userId=" + userId + ", userName=" + userName + ", status=" + status + '}';
}
}
And code to read/parse json string.
JSONObject get_string = new JSONObject(t);
String userid = (String) get_string.get("UserId");
String totalusers = (String) get_string.get("TotalUsers");
String SessionID = (String) get_string.get("SessionID");
int i=0;
JSONObject obj=null;
/* Initialize the List<Contact> */
List<Contact> list=new ArrayList();
while(get_string.has("contacts-"+i))
{
obj=get_string.getJSONObject("contacts-" + i);
Contact contact=new Contact();
contact.setUserId(obj.getString("UserId"));
contact.setUserName(obj.getString("UserName"));
contact.setStatus(obj.getString("Status"));
list.add(contact);
i++;
}

Categories

Resources