How to Convert string to JSON Object? - java

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.

Related

why i am getting org.json.JSONException: Value property of type java.lang.String cannot be converted to JSONObject?

By use of this i'm getting response code and trying to convert String to JSONObject but getting exception.
public JSONObject getJSONFromUrl(String url,List<NameValuePair> nameValuePairsList) {
// Making HTTP request
try {
HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 20000);
HttpConnectionParams.setSoTimeout(param, 20000);
DefaultHttpClient httpClient = new DefaultHttpClient(param);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairsList));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PropertyLogger.debug("URL Request: ", url.toString());
PropertyLogger.debug("Encoded Params: ", nameValuePairsList.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
PropertyLogger.debug("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
PropertyLogger.error("UnSupported Exception", e.toString());
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
String TAG = "PropertyJsonParser";
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();
jsonResp = sb.toString();
PropertyLogger.debug("Content: ", sb.toString());
} catch (Exception e) {
PropertyLogger.error("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
PropertyLogger.error("JSON Parser", "Error parsing data :" + e.toString());
return null;
}
return jObj;
}
You get this error because you are not receiving proper JSON response.
Check your api response and possible also provide your api response.
Because your variable jsonResp contain string value not JSONObject so please first print and make sure is it string type value or not.

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

How to send httpRequest to server with GZIP DATA

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 to get text from JSON without [" "]

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

read JSON file and display its contents

I have the file test.json on my Unix machine which has the data as below
{
"recordId" :10,
"recordName" : "RECORDS",
"records" : [ {
"field1" : 111,
"titleField" : 1,
"titleIDMap" : null,
"titleId" : 500,
"titleStartDate" : "2013-12-22T00:00:00.000+0000",
"titleEndDate" : "2013-12-03T00:00:00.000+0000",
"languageId" : 20
}]
}
Now I'm writing the REST jersey client to read the test.json and show the output as below
public class RestWebServiceClient {
private static String BASE_URL="https://myUrl.com";
public static void main(String[] args) {
JSONParser parser = new JSONParser();
final String auth = "mfndfkndfkdnfkdnfdkfndkfndfkndkfndzxzxzxz==";
try {
Object obj = parser.parse(new FileReader("/home/user/test.json"));
JSONObject jsonObject = (JSONObject) obj;
final String postData = "dataTobePosted";
final String postResult = postJSONData(auth, BASE_URL+"/search",postData);
System.out.println("\n============postResponse============");
System.out.println(postResult);
JSONObject issueObj = new JSONObject(postResult);
}
catch (AuthenticationException e){
System.out.println("Username or Password wrong!");
e.printStackTrace();
} catch (JSONException e) {
System.out.println("Invalid JSON output");
e.printStackTrace();
} catch (ClientHandlerException e) {
System.out.println("Error invoking REST method");
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String postJSONData(String auth, String url, String data) throws AuthenticationException, ClientHandlerException{
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
.accept("application/json").post(ClientResponse.class, data);
int statusCode = response.getStatus();
if (statusCode == 401) {
throw new AuthenticationException("Invalid Username or Password");
}
return response.getEntity(String.class);
}
How do I read the test.json and display its contents?
For recordId :
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("recordId");
System.out.println(name);
For records :
List<String> list = new ArrayList<String>();
JSONArray jsonList = jsonObject.getJSONArray("records");
for (int i = 0; i < jsonList.length(); i++)
list.add(jsonList.getString(i));
Your records data will be inside list object

Categories