Before, i should say, my English is very bad. İm sorry for it.
i parsing wanna Json output, in my android prject. my json file is with url.
it is like there
{
"urun": [
{
"ID": "1011245",
"name": "Jeanne Darc-Elbise-jdje57942xl",
"name_eng": "Jeanne Darc-Dress-jdje57942xl",
"catID": "142",
"tedarikciCode": "jdje57942xl",
"markaID": "30",
"data1": "4",
"resim": "var/30/jdje57942xl/siyah_1_jdje57942xl.jpg",
"resim2": "var/30/jdje57942xl/siyah_2_jdje57942xl.jpg",
"resim3": "var/30/jdje57942xl/siyah_3_jdje57942xl.jpg",
"fiyat": "28",
"ozellik1detay": "44-50"
}
]
}
my parser class is
public class JsonParsers
{
final String TAG = "JsonParsers.java";
static InputStream is =null;
static JSONObject jObj=null;
static String ParserJson=null;
public JsonParsers(String yourJsonStringUrl) {
}
public JsonParsers() {
super();
}
public String getJsonUrl(String url) throws IOException {
try{
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb= new StringBuilder();
String line = "";
while ((line=reader.readLine())!=null)
{
sb.append(line+"\n");
//Log.e("çıktı:",line);
}
is.close();
ParserJson = sb.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
try {
jObj=new JSONObject(ParserJson);
}
catch (JSONException e) {
e.printStackTrace();
}
return ParserJson;
}
}
My asyncTask Class is
private class AsyncTaskParseJSonIncludes extends AsyncTask<String, String, String> {
final String TAG = "MainActivity.java";
JSONArray dataJsonArr = null;
String ObjectStr;
protected String doInBackground(String... path) {
try{
try{
JsonParsers parser = new JsonParsers();
//Json = parser.getJsonUrl(JsonPath);
ObjectStr=parser.getJsonUrl(JsonPath);
JSONObject Json= new JSONObject(ObjectStr);
dataJsonArr=Json.getJSONArray("urun");
for(int i=0;i<dataJsonArr.length();i++)
{
JSONObject c = dataJsonArr.getJSONObject(i);
// Log.e("Deneme", c.getString("name"));
ID.add(Integer.valueOf(c.getString("ID")));
name.add(c.getString("name"));
name_eng.add(c.getString("name_eng"));
//name_py.add(c.getString("name_py"));
CatID.add(Integer.valueOf(c.getString("CatID")));
tedarikciCode.add(c.getString("tedarikciCode"));
markaID.add(Integer.valueOf(c.getString("markaID")));
data1.add(Integer.valueOf(c.getString("data1")));
resimmmm.add(c.getString("resim"));
resim2.add(c.getString("resim2"));
resim3.add(c.getString("resim3"));
fiyat.add(Integer.valueOf(c.getString("fiyat")));
ozellik1detay.add(c.getString("ozellik1detay"));
// ozellik2detay.add(c.getString("ozellik2detay"));
}
for(int i=0;i<name.size();i++) {
Log.e("Deneme", name.get(i));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {}
/////////////////////////////////////////////////////////
}
it is in normaly working but it is not returned json values.
i check the parser class for stream of data, it is fixed.
But it is only first value returned, other datas don't returned.
i don't understand it logical problem. when someone help me for fix my code i very funny. Thanks.
name_eng.add().
where was the name_eng defined?
CatID to catID.
right:
Try{A}catch{}
Try{B}catch{}
Try{C}catch{}
wrong:
Try{A;B;C}catch{}
Try GsonRequest, it's very simple to parse JSON, nice example of use it you have there: USE GsonRequest
Related
I'm programming an app that calculates, in route, two locations. I've implemented the google places API to get the lat/lon based on name or address but I can't implement the Distance API. The classes/methods don't appear when I try to import. Below is an example of what I'm trying to do.
private static final String API_KEY = "YOUR_API_KEY";
private static final GeoApiContext context = new
GeoApiContext().setApiKey(API_KEY);
public DistanceMatrix estimateRouteTime(DateTime time, Boolean isForCalculateArrivalTime, DirectionsApi.RouteRestriction routeRestriction, LatLng departure, LatLng... arrivals) {
try {
DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(context);
if (isForCalculateArrivalTime) {
req.departureTime(time);
} else {
req.arrivalTime(time);
}
if (routeRestriction == null) {
routeRestriction = DirectionsApi.RouteRestriction.TOLLS;
}
DistanceMatrix trix = req.origins(departure)
.destinations(arrivals)
.mode(TravelMode.DRIVING)
.avoid(routeRestriction)
.language("fr-FR")
.await();
return trix;
} catch (ApiException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
The GeoApiContext and DistanceMatrix don't appear at import.
Tks for help.
Answering my question...
public class GetJson extends AsyncTask<Void, Void, DeliveryData> {
#Override
protected void onPreExecute() {
// progressDialog
}
#Override
protected DeliveryData doInBackground(Void... params) {
Utils util = new Utils();
DeliveryData json = util.getInfo("https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins="+latLngCompany.latitude+","+latLngCompany.longitude+
"&destinations="+latPlace+","+lonPlace+"&key=" + APISERVERKEY);
deliveryData.saveDeliveryData();
return json;
}
#Override
protected void onPostExecute(DeliveryData deliveryData) {
//progressDialog.dismiss
}
}
Created a AsyncTask to get json from url with the especifics parameters.
public class Utils {
public DeliveryData getInfo(String end){
String json;
DeliveryData output;
json = NetworkUtils.getJSONFromAPI(end);
output = parseJson(json);
return output;
}
private DeliveryData parseJson(String json){
try {
DeliveryData deliveryData = new DeliveryData();
JSONObject distanceJson = new JSONObject(json)
.getJSONArray("rows")
.getJSONObject(0)
.getJSONArray("elements")
.getJSONObject(0)
.getJSONObject("distance");
Double distanceDouble = null ;
String distance = distanceJson.get("text").toString();
if (distance.contains("km")){
distanceDouble = Double.parseDouble(distance.replace("km", ""));
}else {
distanceDouble = Double.parseDouble("0." + distance.replace("m", ""));
}
deliveryData.setDistance(distanceDouble);
return deliveryData;
}catch (JSONException e){
e.printStackTrace();
return null;
}
}
}
At getInfo, the data from url is passed to string. Then, parseJson is call to transform the string to JsonObject.
My Json there is only one position. So, the object is selected at array and the String is parse to Double, excluding the chars. In the end, the distance is saved at object.
public class NetworkUtils {
public static String getJSONFromAPI (String url){
String output = "";
try {
URL apiEnd = new URL(url);
int responseCode;
HttpURLConnection connection;
InputStream is;
connection = (HttpURLConnection) apiEnd.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.connect();
responseCode = connection.getResponseCode();
if(responseCode < HttpURLConnection.HTTP_BAD_REQUEST){
is = connection.getInputStream();
}else {
is = connection.getErrorStream();
}
output = convertISToString(is);
is.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
private static String convertISToString(InputStream is){
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br;
String row;
br = new BufferedReader(new InputStreamReader(is));
while ((row = br.readLine())!= null){
buffer.append(row);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
}
This class is resposible for connecting to server and get the data from url.
I don't understand why can't I read this json link but Browser Chrome can read, I tried with different link and I read them.
this is the link for requesting json response:
My Code:
runOnUiThread(new Runnable() {
#Override
public void run() {
new sendToken().execute("http://admin:123#qlvb-snv.newsaigonsoft.com/push-notifications-portlet/api/secure/jsonws/pushnotificationsdevice/add-push-notifications-device?token=cNAXYNQSPHk:APA91bF86THzkPE_ol9euea1M40x6jVgN9RjUOISVtL-UEXDYpAP62aeRnUwkLrSt6z8C4saTJPKW5CJ57VSRmovZ5OBX4NsZg3U-zoDdXB64dWzAQGB7WllGvqGEO3Nt4_Fbg-vUyok&platform=android");
}
});
and My AsyncTask:
class sendToken extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return docNoiDung_Tu_URL(params[0]);
}
#Override
protected void onPostExecute(String s) {
Log.d("Respones: ", s + "");
}
}
and it does not respond with anything.
Two things may be the cause
either your method
docNoiDung_Tu_URL is not correct or correctly written
or, You have no permissions to access Internet.
change your doInBackground Like this
class sendToken extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = getNewHttpClient();
HttpGet httpget = new HttpGet(arg0[0]);
// Execute HTTP get Request
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
return responseString;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
Log.d("Respones: ", s);
}
Also add the dependencies to build.gradle
compile('org.apache.httpcomponents:httpcore:4.4.1') {
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
don't forget to add the internet permission to manifest
<uses-permission android:name="android.permission.INTERNET"/>
you have to make http call
HttpURLConnection urlConnection = null;
String My_URL = "YOUR URL";
BufferedReader reader = null;
URL url = null;
String Json;
InputStreamReader inputStream1 = null;
InputStream inputStream = null;
inside do in background
#Override
protected String doInBackground(Void... params) {
try {
url = new URL(My_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if(urlConnection.getResponseCode() == 200)
{
inputStream = urlConnection.getInputStream();
Json = readData(inputStream);
}
else {
urlConnection.getResponseCode();
}
}catch (Exception e){
Json = e.toString();
}
finally {
if (urlConnection!=null)
urlConnection.disconnect();
try {
if (inputStream!=null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return Json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// your work
}
public String readData(InputStream inputStream)
{
StringBuilder builder = new StringBuilder();
try {
if (inputStream != null) {
inputStream1 = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStream1);
String line = reader.readLine();
while (line != null) {
builder.append(line);
line = reader.readLine();
}
} else {
Toast.makeText(MainActivity.this, "errorwa", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){}
return builder.toString();
}
You can not directly read the response from the url.
Try out below code:
public JSONObject getJSONFromUrl(String url) {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Add the below permission in manifest
<uses-permission android:name="android.permission.INTERNET"/>
I am using following code to deserailze the JSON data from Url.
But My Error is:Value {"InvoiceNo":18} of type java.lang.String cannot be converted to JSONObject.My Json Like: "{\"InvoiceNo\":18}" Please Any one Help me.
private class LongOperation extends AsyncTask{
#Override
protected Object doInBackground(Object[] params) {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://192.168.1.2/Json/api/test"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject(responseText); // **Error on this line**
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = null;
try {
value = json.getString(key);
Toast.makeText(Billing.this, value + "",
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
textInvoice.setText(value.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("responseText", responseText);
return null;
}
}
Your String should not contain the character "\". If so, this is the cause of your problem.
I have a json file that I am sending to the server as a POST but it has to be gzipped
I dont know how to do it
I found the potential solution here GZip POST request with HTTPClient in Java
but I dont know how to merge the methodology they used in the second part of the answer with my makeHttpRequest method (they are using a multipart entity and Im using a urlencoded entity)
EDIT: Here is how I get jsonAsBytes
public static byte[] stringToGZIPByteArray (String string) {
Log.d("string to be gzipped", string);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(string.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {
};
}
}
return baos.toByteArray();
} // End of stringToGZIPByteArray
This is where I use that method
jsonParser.sendGzippedJSONviaHTTP(context, API.JSON_ACCEPT, UtilityClass.stringToGZIPByteArray(jsonObject.toString()), context.getResources());
and this is sendGzippedJSONviaHTTP
public JSONObject sendGzippedJSONviaHTTP(Context context, String url, byte[] gzippedJSON, Resources res) {
if (httpClient == null) {
try {
httpClient = new HttpClientBuilder().setConnectionTimeout(10000)
.setSocketTimeout(60000) //
.setHttpPort(80)//
.setHttpsPort(443)//
.setCookieStore(new BasicCookieStore())//
.pinCertificates(res, R.raw.keystore, null) //
.build();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Making HTTP request
try {
// request method is POST
// defaultHttpClient
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Encoding", "gzip");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(AndroidHttpClient.getCompressedEntity(gzippedJSON, context.getContentResolver()));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
reader.close();
json = sb.toString();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
// return JSON String
return jsonObject;
} // End of makeHttpRequest
Take a look at AndroidHttpClient. You can use it instead of appache's DefaultHttpClient. It has a static method getCompressedEntity(byte[] data, ContentResolver resolver)
So, you can write:
HttpPost httpPost = new HttpPost(url);
post.setEntity( AndroidHttpClient.getCompressedEntity( jsonAsBytes, null ) );
httpClient.execute(httpPost);
UPDATE:
this is the code from AndroidHttpClient:
public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver)
throws IOException {
AbstractHttpEntity entity;
if (data.length < getMinGzipSize(resolver)) {
entity = new ByteArrayEntity(data);
} else {
ByteArrayOutputStream arr = new ByteArrayOutputStream();
OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(data);
zipper.close();
entity = new ByteArrayEntity(arr.toByteArray());
entity.setContentEncoding("gzip");
}
return entity;
}
should give you some insights
How do I get text from json without [" "] only text, in Android project?
this is my json from url {"code":200,"lang":"en-ru","text":["Better late than never"]}
i need get text "text":["Better late than never"] without [" "] only text: Better late than never
myclass MAINACTIVITY
public class MainActivity extends Activity {
JSONParser jsonparser = new JSONParser();
TextView tv;
String ab;
JSONObject jobj = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvResult);
new retrievedata().execute();
}
class retrievedata extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
jobj = jsonparser.makeHttpRequest("https://translate.yandex.net/api/v1.5/tr.json/translate?key=YOURAPIKEY&text=Better%20late%20than%20never&lang=ru");
// check your log for json response
Log.d("Login attempt", jobj.toString());
ab = jobj.optString("text");
return ab;
}
protected void onPostExecute(String ab){
tv.setText(ab);
}
}
}
MY JSONPARSER CLASS
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser(){
}
public JSONObject makeHttpRequest(String url){
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
is = httpentity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
json = sb.toString();
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jobj;
}
}
This is a problem with people who aren't that familiar with JSON structure. When I am looking at JSON, I find it easier to pretty-print it, because it makes the structure very clear. In the case of your JSON: {"code":200,"lang":"en-ru","text":["Better late than never"]}, it becomes:
{
"code": 200,
"lang": "en-ru",
"text": [
"Better late than never"
]
}
The error in your code is that you are trying to parse the "text" key of the dictionary as a String, when it is instead, an array containing a string. To correct, replace this
ab = jobj.optString("text");
return ab;
with
JSONArray ar = jobj.optJSONArray("text");
if (ar != null) {
return ar.optString(0);
}
From your json from url {"code":200,"lang":"en-ru","text":["Better late than never"]}
Try this...
Yout JSON structure
{
"code": 200,
"lang": "en-ru",
"text": [
"Better late than never"
]
}
You can get your output using below..
try {
JSONObject jsonObj = new JSONObject(json);
String code = jsonObj.getString("code");
String lang = jsonObj.getString("lang");
JSONArray text = jsonObj.getJSONArray("text");
Log.e("output", "code:" + code + "\nlang:" + lang + "\ntext"
+ text.getString(0));
} catch (Exception e) {
e.printStackTrace();
}