How to get text from JSON without [" "] - java

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();
}

Related

How to Convert string to JSON Object?

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.

Json parsing as logical workout

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

Blogger JSON API Error: Value Not of type java.lang.String cannot be converted to JSONObject

I am trying to fetch blogger blog content into android application, for this I am using Blogger API v3, Whenever I try to fetch JSON object in android app I get an error "Value Not of type java.lang.String cannot be converted to JSONObject" below is my code:
MainActivity:
public class MainActivity extends Activity {
private TextView tmpText;
private final String api_key = "myApiKey";
private final String blog_id = "myBlogId";
private final String url = "https://www.googleapis.com/blogger/v3/blogs/"+blog_id+"?key="+api_key;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tmpText = (TextView) findViewById(R.id.tempText);
new Fetch().execute();
}
private class Fetch extends AsyncTask<String, String, JSONObject> {
JSONObject jsonObject;
#Override
protected void onPreExecute() {
super.onPreExecute();
tmpText.setText("Loading...");
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jsonParser = new JSONParser();
jsonObject = jsonParser.getJSONFromUrl(url);
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject object) {
super.onPostExecute(object);
tmpText.setText(""+object);
}
}
}
JSONParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// 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, "UTF-8"), 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;
}
}
This is JSON Response when fetched through browser:
{
"kind": "blogger#blog",
"id": "myBlogId",
"name": "myBlogName",
"description": "myBlogDesc",
"published": "myBlogPublishedDate",
"updated": "myBlogUpdatedDate",
"url": "myBlogUrl",
"selfLink": "myBlogSelfLink",
"posts": {
"totalItems": 159,
"selfLink": "myBlogTotalItemsSelfLink"
},
"pages": {
"totalItems": 7,
"selfLink": "myBlogTotalPagesSelfLink"
},
"locale": {
"language": "en",
"country": "",
"variant": ""
}
}
Error:
E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Not of type java.lang.String cannot be converted to JSONObject
You are doing POST instead of GET. Use HttpGet instead of HttpPost.

Parse JSON string in android

What I want to do is process live currency JSON strings and retrieve their rate values.
The site I am using returns this:
{"target": "EUR", "success": true, "rate": 0.7298, "source": "USD", "amount": 0.73, "message": ""}
for a URL:
http://currency-api.appspot.com/api/USD/EUR.json?key=KEY
For a conversion of USD to Euros. I want to store the rate in a float. I realise I will have to use GSON or something similar to parse the JSON output of the site, but so far I don't have a solution that works. My current AsyncTask for this looks like this:
class AsyncTest extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params)
{
try {
URL url = new URL("http://currency-api.appspot.com/api/USD/EUR.json?key=KEY");
URLConnection connect = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String jsonObject = "";
String line = "";
while ((line = in.readLine()) != null)
jsonObject += line;
in.close();
Toast.makeText(getApplicationContext(), jsonObject, Toast.LENGTH_LONG).show();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);;
}
}
What exactly is wrong here? It causes a runtime exception. And how would I parse the rate out of this URL?
class AsyncTest extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params)
{
try {
URL url = new URL("http://currency-api.appspot.com/api/USD/EUR.json?key=KEY");
URLConnection connect = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder jsonObject = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null)
jsonObject.append( line );
in.close();
Toast.makeText(getApplicationContext(), jsonObject.toString(), Toast.LENGTH_LONG).show();
JSONObject json = new JSONObject(jsonObject.toString());
///// Parse the Json object right here using getString
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);;
}
}
To parse the JSON object, look at the docs
For example
private void parseJson(JSONObject json){
String target = json.getString("target");
boolean success = json.getBoolean("success");
// If the field is optional, use optXXX
double rate = json.optDouble("rate", 1d);
......
}
try catching the JSONException .

android.os.networkonmainthreadexception error in my request response class for JSON

How should I use my aux class for JSON request, bcoz in android 2,3 work but android 4.x dont work
I read that I need to use Asyntask for fix it, or create thread, I prefer Asyntask but I cant compile it.
How fix my code for asyntask ?
public class Httppostaux {
InputStream is = null;
String result = "";
public JSONArray getserverdata(ArrayList<NameValuePair> parameters, String urlwebserver ){
//conecta via http y envia un post.
httppostconnect(parameters,urlwebserver);
if (is!=null){//si obtuvo una respuesta
getpostresponse();
return getjsonarray();
}else{
return null;
}
}
//peticion HTTP
private void httppostconnect(ArrayList<NameValuePair> parametros, String urlwebserver){
//
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlwebserver);
httppost.setEntity(new UrlEncodedFormEntity(parametros));
//ejecuto peticion enviando datos por POST
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error en la conexión HTTP "+e.toString());
}
}
public void getpostresponse(){
//Convierte respuesta a String
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();
result=sb.toString();
Log.e("getpostresponse"," result= "+sb.toString());
}catch(Exception e){
Log.e("log_tag", "Error conviertiendo el resultado "+e.toString());
}
}
public JSONArray getjsonarray(){
//parse json data
try{
JSONArray jArray = new JSONArray(result);
return jArray;
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
return null;
}}}
You should not perform network operations on main thread 4.0 and above. Read this to know how to perform network operations correctly https://developer.android.com/training/basics/network-ops/connecting.html
Here i put the sample code for how i use Asyc task for api calling, hope it will help for you and modify this code as per your need,
new Read().execute(); // Asyc Task initialization
public class Read extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(); // url executed here and the final value is stored in json obj
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// Here you call the json obj and do your UI binding.
}
}
public JSONObject lastTweet() throws ClientProtocolException, IOException,
JSONException {
HttpClient client = new DefaultHttpClient();
StringBuilder url = new StringBuilder(<your_URL>);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
Log.e("RESPONSE VALUE IS", data); // Here you get the response
JSONObject last = new JSONObject(data);
return last; //here the response value is returned
} else {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT);
return null;
}
}
In your manifest.xml don't forget to add this permission <uses-permission android:name="android.permission.INTERNET" />

Categories