JSON parsing problem - java

i am trying to Json parsing in my android app the link is https://www.buzzador.com/apps/present_software/webservice/index.php?op=ProductQ&campaign_id=607&userid=10776
when i put it into Json object it gives errors to me
error is :
08-31 14:40:52.281: WARN/System.err(416): org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
public static String getmyproductquestiondetails(String userid,
String campaignid) {// https://www.buzzador.com/apps/present_software/webservice/index.php?op=EducationResult&userid=1&questionid=1,2,3&answergivenbyuser=1,1,0
String data = null;
try {
URL url = new URL(
"http://dignizant.com/buzz/webservice/index.php?op=getProductQuestion&userid="
+ userid + "&campaign_id=" + campaignid);
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url
.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Utils utils = new Utils();
try {
data = utils.convertStreamToString(http.getInputStream());
System.out.println("getproduct details response :: " + data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
data = e.toString();
}
return data;
}
try {
JSONObject jo = new JSONObject(response);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

char[] utf8 = null;
StringBuilder properString = new StringBuilder("");
utf8 = Response.toCharArray();
for (int i = 0; i < utf8.length; i++) {
if ((int) utf8[i] < 65000) {
properString.append(utf8[i]);
}
}
System.out.println("Response of Login::"
+ properString.toString());

Had similar problem. At first my app was working great on both androids 4.0+ and 4.0- (2.3.3 2.2 etc). after a revision i have that problem. JSonarray could parse on 2.3.3
PROBLEM: Json STRING (response from server) comes with a character ' in front
so actual response= '[{"1":"omg"}] and not the correct one [{"1":"omg"}]
Solution:
if string dosent start with [ then edit response string (remove the ' character)
if (result.startsWith("["))
{
}
else
{
result= result.substring(1);
}
after then everything worked fine for me

If you are a using json-lib-2.4 as library, which I assume, you can parse strings with :
JSONSerializer.toJSON(yourString).toString()
instead of using the JsonObject class

To remove character like (\n) or unwanted character in json string used commons-lang3:3.4 library in program . i used this class to remove unwanted character in json string "StringEscapeUtils.unescapeJava(string)".
this will help you.

Related

Java/Yahoo Finance Retrieving Quotes, Error 401

Here's my Java code to download historical Yahoo finance quotes using crumbs. Sorry, it's not the most efficient code. I'm still learning Java. Everything looks correct to me, but I get error 401 after picking up the crumb and trying to make the second access to "https"//query1.finance.yahoo.com..."
Any ideas of what I'm doing wrong?
URL myUrl = null;
try {
myUrl = new URL("https://finance.yahoo.com");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection urlConn = null;
try {
urlConn = myUrl.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
urlConn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String headerName=null;
String crumb = null;
for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
crumb = cookie.substring(cookie.indexOf("=") + 1, cookie.indexOf("&"));
}
}
StringBuilder qUrl = new StringBuilder();
qUrl.append("https://query1.finance.yahoo.com/v7/finance/download/AAPL");
qUrl.append("?period1=" + 1495813803L);
qUrl.append("&period2=" + 1497887408L);
qUrl.append("&interval=1d");
qUrl.append("&events=history");
qUrl.append("&crumb=" + crumb);
URL url = null;
try {
url = new URL(qUrl.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection conn;
InputStream is = null;
try {
conn = url.openConnection();
String redirect = conn.getHeaderField("Location"); // Can handle one redirection
if(redirect != null ) {
conn = new URL(redirect).openConnection();
}
is = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}

The given code is returning me an empty JSON output

void url_get(double lati,double longi) {
URL url = null;
try {
url = new URL("https://maps.googleapis.com/maps/api/place/search/json?&location="+lati+","+longi+"&radius=1000&types=hospital&sensor=true&key=MY_KEY);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
TextView json = (TextView) findViewById(R.id.json3);
String theString = IOUtils.toString(in, "UTF-8");
json.setText(theString);
//System.out.println(in);
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
}
The code was working fine when I had hardcoded the latitude and longitude values.However when I tried to pass the values of latitutde and longitude through the function,It dint get recognized.I suppose the URL wasnt built properly.Could you please suggest a way to build my url with the values of latitude and longitude?
You should convert the values to string using:
Double.toString(double);
or:
String.valueOf(double);
So your string should be something like this:
url = new URL("https://maps.googleapis.com/maps/api/place/search/json?&location="+String.valueOf(lati)+","+String.valueOf(longi)+"&radius=1000&types=hospital&sensor=true&key=MY_KEY");
Note
In your code a " is missing at the end of the string.

Parse oData response in Java

I am creating a Http request to access OData services. I am getting the response but I don't know how to parse the response into a String objects so that I can add them to a ArrayList.
Here is my code:
protected List<StatusResponse> doInBackground(Void... params)
{
// TODO Auto-generated method stub
// Execute HTTP Post Request
mResponseList = new ArrayList<StatusResponse>();
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(myOdataQueryUrl);
try
{
HttpResponse responsenext = httpclient.execute(httpget);
HttpEntity entitynext = responsenext.getEntity();
AddedResult= EntityUtils.toString(entitynext);
jsonArray = new JSONArray(AddedResult);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject menuObject = jsonArray.getJSONObject(i);
String createdBy = menuObject.getString("CreatedBy");
String comment = menuObject.getString("Comment");
String location = menuObject.getString("Location");
String slot = menuObject.getString("Slot");
String reachingAt = menuObject.getString("StartTime");
String lunch = menuObject.getString("Lunch");
mResponseList.add(new StatusResponse(createdBy, comment, location, slot, reachingAt, lunch));
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mResponseList;
}
I get this response:--
{
"odata.metadata":"mysite/odata/$metadata#OStatus","value":[
{
"StatusId":2151,"Location":"Office","Slot":"Running late","StartTime":"2014-09-29T12:30:00","Comment":"-","Lunch":null,"CreatedBy":"","ModifiedBy":null,"Created":"2014-09-29T04:39:10.443","Modified":null
}
]
}
I get the following error if I try to parse it like above:
Value {"value":[{"Created":"2014-09-29T04:39:10.443","Modified":null,"StatusId":2151,"ModifiedBy":null,"Slot":"Running late","CreatedBy":"","Comment":"-","Location":"Office","Lunch":null,"StartTime":"2014-09-29T12:30:00"}],"odata.metadata":"https:\/\/mySite\/odata\/$metadata#OStatus"} of type org.json.JSONObject cannot be converted to JSONArray
You're trying to convert a normal JSON object into a JSON Array.
It also seems that you're declaring that array to be a field in stead of a local variable to your method. Are you sure that is what you need?

Retrieving facebook graph data for android native app

I'm creating a android game that integrates with facebook to retrieve their photo and first name and other information using the graph, I've found out how to retrieve their photo using the below code which works perfectly but I'm struggling to find working examples of extracting other information like first_name etc...
The code I'm using to retrieve the photo and display it in a ImageView is below.
public void showPhoto(View v) {
try {
ImageView MyProfilePicImageView = (ImageView)findViewById(R.id.temp);
URL MyProfilePicURL = new URL("https://graph.facebook.com/me/picture?type=normal&method=GET&access_token="+ access_token );
Bitmap MyprofPicBitMap = null;
try {
MyprofPicBitMap = BitmapFactory.decodeStream(MyProfilePicURL.openConnection().getInputStream());
MyProfilePicImageView.setImageBitmap(MyprofPicBitMap);
}
catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
I've searched high and low but can't seem to find information on how to retrieve the other information using the graph, other information meaning first_name etc... including here on the facebook developer website (https://developers.facebook.com/docs/reference/api/) but can't find a working example.
Can anybody show me a working example to retrieve the first_name of the user so I can display it in a textview?
using this url"https://graph.facebook.com/me/friends?access_token="+accessToken you can get your friends which contains thier names and ids to get info about any of them just use `"https://graph.facebook.com/"+yourFriendId+"?access_token="+accessToken'
this will return json that you can parse and useExample
HttpClient httpclient = new DefaultHttpClient();
String url = "https://graph.facebook.com/me/friends?access_token=" + URLEncoder.encode(token);
HttpGet httppost = new HttpGet(url);
try {
HttpResponse response = httpclient.execute(httppost);
// to get the response string
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
// used to construct the string
String res = "";
for (String line = null; (line = reader.readLine()) != null;) {
res += line + "\n";
}
// here we will parse the response
JSONObject obj = new JSONObject(new JSONTokener(res));
JSONArray data = obj.getJSONArray("data");
int len = data.length();
for (int i = 0; i < len; i++) {
JSONObject currentResult = data.getJSONObject(i);
String name = currentResult.getString("name");
String icon = currentResult.getString("id");
// do what ever you want
}
} 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();
}
If you change your request URL to just /me (i.e. https://graph.facebook.com/me?type=normal&method=GET&access_token=...) you'll get all available profile information for the currently authenticated user.
This JSON object should have first_name and last_name, among other attributes foud here.
Check out this handy API explorer tool to play around with what you should be seeing.

String from server cannot be converted to JSONObject?

My server returns a JSON object via the body of an HTTP POST response, but I get the this error when my app tries to convert the string into a JSONObject:
06-02 09:05:34.380: E/JSONException_MyAppService(19913): org.json.JSONException: Value {"VALS":{"VAL1":"hello","VAL2":"hello2","VAL3":"hello3"}} of type java.lang.String cannot be converted to JSONObject
It looks like my server is returning a acceptable JSON encoded string, but it just won't convert to a JSONObject. I even changed the content-type of the server's response header to "application/json". Please help me fix this, I've been trying all day.
EDIT- I use the following code:
try {
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = client.execute(post, responseHandler);
JSONObject response=new JSONObject(responseBody);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("IO_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("JSONException_"+TAG,""+e);
}
I also tried imran khan's suggestion:
try {
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
String retSrc = EntityUtils.toString(entity);
// parsing JSON
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
JSONArray tokenList = result.getJSONArray("VALS");
JSONObject oj = tokenList.getJSONObject(0);
String token = oj.getString("VAL1");
String token1 = oj.getString("VAL2");
String token11 = oj.getString("VAL3");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("IO_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("JSONException_"+TAG,""+e);
}
:'( :'(
How are you doing it? It should work with:
JSONObject object = new JSONObject (yourString);
You can convert string to json as:
String str="{\"VALS\":{\"VAL1\":\"hello\",\"VAL2\":\"hello2\",\"VAL3\":\"hello3\"}}";
try {
JSONObject result = new JSONObject(str);
JSONObject resultf = result.getJSONObject("VALS");
Toast.makeText(this, resultf.getString("VAL1").toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, resultf.getString("VAL2").toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, resultf.getString("VAL3").toString(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
String retSrc = EntityUtils.toString(entity);
// parsing JSON
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
JSONObject object2 = result.getJSONObject("VALS");
String token = object2.getString("VAL1");
String token = object2.getString("VAL2");
String token = object2.getString("VAL3");
}
}
catch (Exception e) {
}
I FIXED IT! It was entirely my server's fault. It turned out that my server was responding incorrectly. What happened was there was a bug within the web framework and after updating to the latest version, the problem solved itself. I'm guessing the old version of the web framework returned the incorrect content-type response header, or used some weird encoding.
So everyone's Java code here should be 100% correct, because Java was not at fault here. THANKS FOR ALL YOUR EFFORT!
Miguel's answer was the closest explanation, so I will accept his answer.

Categories

Resources