How to put list object to JSon object - java

In servlet I am trying to put a list in json object, but i cant able to find what is the error. I am calling servlet from ajax call, Here is servlet code,
Latlng latlng=new Latlng();
List<Latlng> vehicleList = new ArrayList<Latlng>();
sql ="SELECT a.vehicleno,a.lat,a.lng,a.status,a.rdate,a.rtime from latlng a,vehicle_details b where a.vehicleno=b.vehicleno and b.clientid="+clientid +" and b.groupid in(select groupid from group_details where groupname='"+gname+"' and clientid='"+clientid+"')";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
String s=resultSet.getString("vehicleno");
latlng.setVehicleno(resultSet.getString("vehicleno"));
latlng.setLat(resultSet.getString("lat"));
latlng.setLat(resultSet.getString("lng"));
latlng.setLat(resultSet.getString("status"));
latlng.setLat(resultSet.getString("rdate"));
latlng.setLat(resultSet.getString("rtime"));
vehicleList.add(latlng);
System.out.println(vehicleList);
String json = new Gson().toJson(vehicleList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
is there anything wrong in it. It is not even displaying exception also.

Try like this.
while (resultSet.next()) {
latlng=new Latlng();
String s = resultSet.getString("vehicleno");
latlng.setVehicleno(resultSet.getString("vehicleno"));
latlng.setLat(resultSet.getString("lat"));
latlng.setLat(resultSet.getString("lng"));
latlng.setLat(resultSet.getString("status"));
latlng.setLat(resultSet.getString("rdate"));
latlng.setLat(resultSet.getString("rtime"));
vehicleList.add(latlng);
}
System.out.println(vehicleList);
String json = new Gson().toJson(vehicleList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

Related

string value to JSON object in java but No value for

response
deneme2="{\"NUKE_USER_NO\":\"1494\",\"WEB_PIN\":\"metin\",\"CARI_NO\":\"2611\",\"FIRMA_ADI\":\"\",\"CARI_UNVANI\":\"LTDSTI\",\"MOD\":\"Müşteri\",\"RENK\":\"'#fbbb5e'\",\"EMAIL\":\"yok\",\"SAHIS_NO\":\"9\",\"ADISOYADI\":\"Metin\",\"YETKILER\":\"UrunListesi, KampanyaList, YeniUrunler, SepetListe, SiparisTakip, BekleyenSiparisler, TaksitBilgi, TaksitliOdeme, CariEkstre, HavaleEftBildir, BankaHesapNumaralari, PcShirbazi, IadeTalep, IadeSonuclari, GarantiSorgulama, ArizaTakip, UyelikBilgilerim, KullaniciList, SevkAdres, CariHareketler, BorcAlacakDurumu, AlisAnalizi, AlisCirolari, BABS, StandartFormlar, ArizaIadeProseduru, SevkiyatProseduru, Organizasyon, Iletisim, SiparisVerme, GuvenliOdeme3D, MailOrderOranlari, KargoTakip, FiyatMod, AnaSayfa, MusteriTemsilcisiniGorsun, Ihaleler, Puanlarim, UyeIsyeri, IadeDegerlendir, IadeSonucDepo\",\"CARI_TIP_NO\":\"6\",\"AKTIF_SEPET\":\"197\",\"KAR_MARJI\":\"0\",\"ODEME_NO\":\"21\",\"DOVIZ_BIRIMI\":\"USD\",\"NAKLIYE_TIP_NO\":\"11\",\"ROLE_ADI\":\"Bayi\"}";
Java code
public JSONObject stringToJson(String deneme2)
{
JSONObject json= new JSONObject();
try {
json.getString(deneme2);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
and then error and exception. It doesn't change string value JSONObject
http://i.stack.imgur.com/roVu5.png
Firstly:
JSONObject json= new JSONObject();
is not taking the actual String which need to be converted.
public JSONObject stringToJson(String deneme2)
{
JSONObject json= new JSONObject(deneme2); //pass a String here
try {
json.getString("key name"); //key for which you need to retrieve data
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
Hope it helps.
deneme2 is string value and deneme2 is JSON writing format. and then i sent deneme2 stringToJson function for string to JSON object bu return exceptation in image and null json.
Try this it will help you : Firstly convert above String to json object
JSONObject jsonobject = new JSONObject(deneme2);
try {
String abc = json.getString("NUKE_USER_NO");
Log.i("Log", abc);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to get values and keys through single line string xml in android [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 8 years ago.
I am encounter a problem. I have following xml
<string>[{"BatchIDs":[],"HomeWorkCategoryName":"","FileURL":"","FileName":"","ID":1,"Title":"test","Description":"test","HomeworkCategoryID":1,"ExpiryDate":"\/Date(1386658800000)\/","FileID":-2147483648,"URL":"","Mode":1,"Type":2,"Status":1,"CreatedOnDate":"\/Date(1388093500883)\/","UpdatedOnDate":"\/Date(1388093500883)\/","Inactive":false,"Deleted":true},
{"BatchIDs":[],"HomeWorkCategoryName":"","FileURL":"","FileName":"","ID":1,"Title":"test","Description":"test","HomeworkCategoryID":1,"ExpiryDate":"\/Date(1386658800000)\/","FileID":-2147483648,"URL":"","Mode":1,"Type":2,"Status":1,"CreatedOnDate":"\/Date(1388093500883)\/","UpdatedOnDate":"\/Date(1388093500883)\/","Inactive":false,"Deleted":true},
{"BatchIDs":[],"HomeWorkCategoryName":"","FileURL":"","FileName":"","ID":1,"Title":"test","Description":"test","HomeworkCategoryID":1,"ExpiryDate":"\/Date(1386658800000)\/","FileID":-2147483648,"URL":"","Mode":1,"Type":2,"Status":1,"CreatedOnDate":"\/Date(1388093500883)\/","UpdatedOnDate":"\/Date(1388093500883)\/","Inactive":false,"Deleted":true}]
And I want to read all values passed in this xml. This xml is single string return by web service. Currently I am using following code (it's also providing null value for first entry)
Object result = envelope.getResponse();
str=result+"";
String key,value;
String[] couple = str.split(",\"");
for(int i =0; i < couple.length ; i++) {
String[] items =couple[i].split(":");
key=items[0];
value=items[1];
key=key.replaceAll("\"", "");
value=value.replaceAll("\"", "");
/* some conditions to fetch values */
}
Please tell me how can I get exact values and keys in android.
Thanks,
It seems to be a valid json. You can use http://jsonlint.com/ to check that.
So with this following class : JSONArray, you can retrieve what you want.
Thanks everyone for helping me.
Here is my soluction through I overcome my problem. May be it will use for others
HttpGet httpRequest = new HttpGet(_URL);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpresponse = httpclient.execute(httpRequest);
JSONArray response = null;
try {
response = new JSONArray(getJSONString(httpresponse));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < response.length(); i++) {
try {
//your values
String _name=response.getJSONObject(i).getString("NAME");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is 2nd function.If your function is parse through xml code.
public static String getJSONString(HttpResponse response) {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(response.getEntity().getContent());
NodeList nl = doc.getElementsByTagName("string");
Node n = nl.item(0);
String str = n.getFirstChild().getNodeValue();
return str;
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Happy Coding

JSON io writer delete JSONObject on Android

I'm currently using the library JSON-io. I created a desktop application which when a person want to log in in the system send an JSONObject with his username and password. Then the server send back the response if the person is allowed or not (also a JSONObject). Until here everything works fine.
Now i want to make an Android app. I take the same code than before for login but the application crashes.
The code for login is launch from an AsyncTask and i put the permission to access to Internet to the Manifest.
I perform some testing and it occurs that the method write of JSONWriter "delete" my JSON because on the server side he receives this : {}. I tried to hardcode the JSONObject on the server side (the server's code works fine because we can use the desktop app) but this time the readObject on the android App receives also {}.
We tried to send jsonObject.toString() and this time it worked (except that the server isn't configured to handle a string).
Do anyone knows why on android the two methods write and readObject are deleting the JSON ?
Thank you.
EDIT:
Here the code i wrote:
On the android App
protected Boolean doInBackground(Void... params) {
// 3 : create a JSON object and send it to server for verification
JSONObject loginJS = new JSONObject();
try {
loginJS.put("type", Type.LOGIN); // Type is an enum
loginJS.put("username", userName);
loginJS.put("hash", mPassword);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User user = new User();
System.out
.println("User created and ready to connect to the spu for login");
user.connexionToSPU(); // This method works
System.out.println("LoginJS = "+loginJS.toString()); At this point the print of the JSON is fine we have {"type":"Login", ....}
user.sendToSPU(loginJS); //This is where there's a problem
// 4 : wait response
JSONObject loginResponseJS = user.receiveFromSPU(); // And when i hard code the JSON on the server side receiveFromSPU get a empty JSON
Method connexionToSPU:
public void connexionToSPU() {
jswSPU = null;
jsrSPU = null;
Socket socket = null;
try {
socket = new Socket(prop.readPropertiesXML("IP_adress_server"),
Integer.parseInt(prop.readPropertiesXML("port_server")));
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jswSPU = new JsonWriter(socket.getOutputStream());
jsrSPU = new JsonReader(new BufferedInputStream(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sendToSPU method
public void sendToSPU(JSONObject json) {
try {
jswSPU.write(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ReceiveFromSPU method
public JSONObject receiveFromSPU() {
JSONObject json = null;
try {
json = (JSONObject) jsrSPU.readObject();
System.out.println("JSON FROM THE SERVER : "+json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
Hope it will be sufficiently clear.
Thank you

Java - Jackson to a file

I have a JSON file like this:
{
"Product":
{
"ID": "08-17-96-71-D9-68",
"Licences":
{
"total": 40,
"used": 0,
"remain": 40
}
}
}
I used jackson to convert it to a Java Object and I get all the values (so far, so good).
My problem is that I want to change these values and re-write the JSON file but when I do that, the result is like this:
"{\"Product\":{\"IaD\": \"08-17-96-71-D9-68\",\"Licences\":{\"total\": 40,\"used\": 1,\"remain\": 39}}}"
So when I tried to read it again it gives me an error because it cannot read the first and last character (") and also it reads the \ character.
This is my code:
public class UsingJason {
String theJsonString = "";
ObjectMapper mapper = new ObjectMapper();
public class Product{
Licences lic;
public class Licences{
int total;
int used;
int remain;
}
}
public void readJson(){
if(new File("asset/testJson.json").exists()){
theJsonString = "";
try {
BufferedReader in = new BufferedReader(new FileReader("asset/testJson.json"));
String line;
while ((line = in.readLine()) != null){
theJsonString += line;
}
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("JSON String: "+ theJsonString);
}else{
System.out.println("NO FILE FOUND");
}
JsonNode rootNode = null;
try {
rootNode = mapper.readValue(theJsonString, JsonNode.class);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JsonNode totalNode = rootNode.get("Product").get("Licences").get("total");
JsonNode usedNode = rootNode.get("Product").get("Licences").get("used");
JsonNode remainNode = rootNode.get("Product").get("Licences").get("remain");
JsonNode idStringNode = rootNode.get("Product").get("ID");
// Parse it into a Java object.
try {
int totalObject = mapper.readValue(totalNode, Integer.class);
System.out.println("INTEGER? HAS TO BE... 40: "+totalObject);
String idString = mapper.readValue(idStringNode, String.class);
System.out.println("String? Has to be 08-17-96-71-D9-68: "+idString + " True? "
+ idString.equals("08-17-96-71-D9-68") );
int usedObject = mapper.readValue(usedNode, int.class);
int remainObject = mapper.readValue(remainNode, int.class);
System.out.println("Going to rest 1");
usedObject ++;
remainObject = totalObject - usedObject;
String toJackson = "{\"Product\":{\"I\\D\": \"08-17-96-71-D9-68\",\"Licences\":{\"total\": "+totalObject+",\"used\": "+usedObject+",\"remain\": "+remainObject+"}}}";
System.out.println("String created: " +toJackson);
// THIS toJackson String returns the string without \ and without the "
// IT PRINT THIS: {"Product":{"ID": "08-17-96-71-D9-68","Licences":{"total": 40,"used": 1,"remain": 39}}}
// EXACTLY WHAT I WANT TO Write in the Json file but it writes the \ ..
mapper.writeValue(new File("asset/testJson.json"), toJackson);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anyone tell me what I am doing wrong?
In your code here:
mapper.writeValue(new File("asset/testJson.json"), toJackson);
You are serializing not an object, but the string to the file. I suppose this is the reason why it gets escaped, like any string.
The input value should be an object with your structure.
Something like this:
// Initialize an object
Product myProduct = new Product();
myProduct.lic = new Procuct.Licences();
myProduct.lic.total = totalObject;
myProduct.lic.used = usedObject;
myProduct.lic.remain = remainObject;
// Serialize the object into JSON
mapper.writeValue(new File("asset/testJson.json"), myProduct);

Error Parse JSON Response String Android

I have a response String from an API service like this :
{"id":"login","status":"true"}
and This is the way to parse Response String to get Value from Key "Status"
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
}
catch(JSONException e){
e.printStackTrace();
}
JSONArray innerJsonArray = null;
try {
innerJsonArray = jsonObj.getJSONArray("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObject = null;
try {
jsonObject = innerJsonArray.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println(jsonObject.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and I've got error
"org.json.JSONArray cannot be converted to JSONObject"
Anyone can give me suggestion?
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
System.out.println(jsonObj.getString("status"));
}
catch(JSONException e){
e.printStackTrace();
}
You do not need to bother with any other arrays.
In which line you get the exception ? In any way may be you should use
jsonObj =JSONObject.fromObject(responseString);
Kindly try the snippet code below. Try this link for gaining better knowledge about parsing an JSON response.
JSONObject jObj;
try {
jObj = new JSONObject(responseString);
Log.i("id==", jObj.getString("id"));
Log.i("status==", jObj.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories