json String in android - android

I have a problem while creating jsonStringer in android. My problem is I have to post values to server using post method.So for that I have to send an array. { "name":"asdf","age":"42","HaveFiles":["abcfile","bedFile","cefFile"]} .
So how can I create a json array for haveFiles? And I don't know the no of files it may varies. So I am creating a string builder and appending the values to that.
when I print the jsonString the stringbuilder show that instead of " it shows \". But when I print the string builder it looks ["abcFile"] like this. but in jsonStringer it prints ["\""abcFile\""]. How I can resolve this issue?

Use this to create json object and pass the json object
try {
JSONObject jObj = new JSONObject(YourString);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
If you want jsonArray then
jobj.getJSONArray(TAG_NAME);

It is really simple, you can use GSON library to do it.
The usage is something like:
Gson gson = new Gson();
String jsonStr = gson.toJson(yourObj);
YourObjType yourObj2 = gson.fromJson(jsonStr, YourObjType.class);
Regarding to your situation, you can do:
Gson gson = new Gson();
String[] ss = new String[] {"abcFile", "defFile", "ghiFile"};
String jsonStr = gson.toJson(ss);
And the result of jsonStr is:
["abcFile, defFile, ghiFile"]

Related

How should I parse JSON?

I am trying to parse this json.
However, it is not working ...
I want to parse expected_departure_time of all the buses such as 4 , 15, C1, 4A in departure
this is my code which is not working.
try{
String str = response.getString("departures");
JSONArray jsonArray = response.getJSONArray(str);
JSONObject bus = jsonArray.getJSONObject(0);
String four = bus.getString("expected_departure_time");
textView.append(four);
}catch (JSONException e){
e.printStackTrace();
}
JSON
https://transportapi.com/v3/uk/bus/stop/6090282/live.json?app_id=d7180b02&app_key=47b460aac35e55efa666a99f713cff28&group=route&nextbuses=yes
The error you're making is that you're considering "departures" as a JsonArray, which is not the case in your JSON example, it is a JsonObject (Which in my opinion is a poor way of constructing this Json).
Anyway, you will have to get all the JsonObjects inside the "departure" JsonObject by doing this:
try
{
String jsonString=response.toString();
JSONObject jObject= new JSONObject(jsonString).getJSONObject("departures");
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONArray innerJArray = jObject.getJSONArray(key);
//This is your example, you can add a loop here
innerJArray(0).getString("expected_departure_time");
}
}
catch (JSONException e)
{ e.printStackTrace(); }
If you need to use the transport API for other features, to convert JSON strings to Java objects, you can map automatically by using GSON.
Follow the instructions from Leveraging the gson library and map any response you want from this API.

Convert Base64 string to JSON in android

I have Base64 Encoded string and want to convert it to JSON object.
Here is encoded String
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQU...
Here is how i am doing.
String json = {"image": encode_string};
try{
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
}catch (Throwable t){
t.printStackTrace();
}
But when i write this line String json = {"image":encode_string};i got compile time error.
Unexpected Token
How to resolve that Thanks in advance.
You could make the JSONObject like a HashMap instead of having it parse a string.
This also removes the need for the try-catch.
JSONObject obj = new JSONObject();
obj.put("image", encode_string);
String json = {"image": encode_string};
The right side of this equation doesn't return string value. Instead what you should do is:
String json = "{" + "\"image\":" + encode_string + "}";

Parsing JsonArray With JsonObject

I have some JSON with the following structure:
{
"items":[
{
"product":{
"product_id":"some",
"price_id":"some",
"price":"some",
"title_fa":"some",
"title_en":"Huawei Ascend Y300",
"img":"some",
"has_discount_from_price":"0",
"discount_from_price":null,
"type_discount_from_price":null,
"has_discount_from_product":"0",
"discount_from_product":null,
"type_discount_from_product":null,
"has_discount_from_category":"0",
"discount_from_category":null,
"type_discount_from_category":null,
"has_discount_from_brand":"0",
"discount_from_brand":null,
"type_discount_from_brand":null,
"weight":null,
"features":[
{
"feature_value":"#000000",
"feature_id":"some",
"feature_title":"some"
},
{
"feature_value":"some",
"feature_id":"1652",
"feature_title":"some"
}
]
},
"number":1,
"feature_id":"56491,56493",
"price_inf":{
"has_discount":0,
"discount_type":0,
"final_price":"400000",
"value_discount":0
},
"cart_id":13
}
]
}
I'm trying to access the elements "product_id" and "price_id" with the following Java code:
try{
JSONArray feedArray=response.getJSONArray("items");
for (int i=0;i<feedArray.length();i++){
JSONObject feedObj=feedArray.getJSONObject(i);
JSONObject pro=feedObj.getJSONObject("product");
Product product = new Product();
product.setPrice(pro.getDouble("price_id"));
product.setTitle_fa(pro.getString("price_id"));}}
but i see product not found error.what is wrong in my parser?
First of all your JSON is valid. So no worries there.
Now regarding your problem, because you haven't posted the logs so I can't tell what the exact problem is. But using this code snippet you can get the desired values.
try {
JSONArray itemsJsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < itemsJsonArray.length(); i++){
JSONObject itemJsonObject = itemsJsonArray.getJSONObject(i);
JSONObject productObject = itemJsonObject.getJSONObject("product");
String productId = productObject.getString("product_id");
String priceId = productObject.getString("price_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Validate and create Pojo for your json here
use
Data data = gson.fromJson(this.json, Data.class);
follow https://stackoverflow.com/a/5314988/5202007
By the way your JSON is invalid .
you are getting a json object from your response not json array you need to make following changes
JSONObject temp =new JSONObject(response);
JSONArray feedArray=temp.getJSONArray("items");
Try converting response string to JSONObject first
try{
JSONObject temp =new JSONObject(responseString); // response is a string
JSONArray feedArray=.getJSONArray("items");
....
}
You may try to use GSON library for parsing a JSON string. Here's an example how to use GSON,
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

Iterating through JSON data converted from multidimensional array

THIS WORKS FINE
I have this code block to read a json data that I am getting from FetchData.php file; My code looks like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/mydummyproject/FetchData.php");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
String name = object.getString("name");
String verion = object.getString("version");
textView.setText(name + " - " + verion);
}
catch (JSONException e) {
e.printStackTrace();
}
Data from my PHP File FetchData.php
{"name":"John Doe","version":"Android 4.4"}
PROBLEM
I also have another type of data coming from FetchDataTwo.php
[{"name":"John Doe","version":"Android 4.4"}, {"name":"Seliana Gomez","version":"Android 4.1"}, {"name":"Nerdy Trumph","version":"Android 4.4"}]
Now the above one is also a json data that I have got by doing json_encode($multidimensional_array) in PHP file.
ISSUE
How to loop over this multidimensional encoded array from json. So that I can iterate over like this (json data by json data):
[NOTE: Below is the data that I need to fetch, I don't want to arrange in the displayed fashion. That's just for clarity and example]
Name | Version
John Doe | Android 4.4
Seliana Gomez | Android 4.1
Nerdy Trumph | Android 4.4
Basically as a logic something like this:
//Loop over each json object
for data in JSONObject:
// Print name and version
textView.setText(data.name + " - " + data.version)
It looks like all you have to do is iterate over the JSONArray
try {
JSONArray array = new JSONArray(inputString);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.optJSONObject(i);
// Json Object handling...
}
} catch (JSONException e) {
// handle
}
But really, using Gson should be way easier. It can parse the contents for you into a simple java object. You can annotate a POJO class with the field names and Gson does all the work.
public class NameVersionPair {
private interface Json {
String NAME = "name";
String VERSION = "version";
}
#SerializedName(Json.NAME)
private String mName;
#SerializedName(Json.VERSION)
private String mVersion;
public String getName() {
return mName;
}
public String getVersion() {
return mVersion;
}
}
Then use a Gson instance to parse your string automatically
Gson gson = new Gson();
NameVersionPair[] result = gson.fromJson(inputString, NameVersionPair[].class);

Creating a JSON response from Google Application Engine

Purely as an academic exercise I wanted to convert one of my existing GAE applets to return the response back to Android in JSON and parse it accordingly.
The original XML response containing a series of booleans was returned thus:
StringBuilder response = new StringBuilder();
response.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
response.append("<friend-response><added>");
response.append(friendAdded);
response.append("</added><removed>");
response.append(friendRemoved);
response.append("</removed><found>");
response.append(friendFound);
response.append("</found></friend-response>");
I want to replace this with a JSON response that looks something like this:
{ "friendResponse" : [ { "added":true, "removed":false, "found":true } ]}
I think I can generate the array contents as follows (I haven't tested it yet) but I don't know how to create the top-level friendResponse array itself. I can't seem to find any good examples of creating JSON responses in Java using the com.google.appengine.repackaged.org.json library. Can anyone help put me on the right path?
boolean friendAdded, friendRemoved, friendFound;
/* Omitted the code that sets the above for clarity */
HttpServletResponse resp;
resp.setContentType("application/json");
resp.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
try {
//How do I create this as part of a friendResponse array?
json.put("added", friendAdded);
json.put("removed", friendRemoved);
json.put("found", friendFound);
json.write(resp.getWriter());
} catch (JSONException e) {
System.err
.println("Failed to create JSON response: " + e.getMessage());
}
You need to use JSONArray to create the (single-element) array that will store your object:
try {
JSONObject friendResponse = new JSONObject();
friendResponse.put("added", friendAdded);
friendResponse.put("removed", friendRemoved);
friendResponse.put("found", friendFound);
JSONArray friendResponseArray = new JSONArray();
friendResponseArray.put(friendResponse);
JSONObject json = new JSONObject();
json.put("friendResponse", friendResponseArray);
json.write(resp.getWriter());
} catch (JSONException e) {
System.err
.println("Failed to create JSON response: " + e.getMessage());
}
You can use GSON: https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples
With this framework, you can serialize an object to json, and vice versa.

Categories

Resources