I am getting mismatch in json data after parsing it from API - java

I am trying to parse a json api for Covid19. The link is available in the code . The data I am getting does not match with the original JSON file.(for eg: there is a mismatch in the stats for the district "Rohtas" and many more)
public static void getAllDistrictsInfo()
{
ArrayList<StateDetails> states = new ArrayList<StateDetails>();
try{
URL url = new URL("https://api.covid19india.org/state_district_wise.json");//your url i.e fetch data from .
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
Scanner sc = new Scanner(url.openStream());
String inline = "";
while(sc.hasNext())
{
inline+=sc.nextLine();
}
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject)parse.parse(inline);
ArrayList<String> set = new ArrayList<String>(jobj.keySet());
for(Iterator iterator = set.iterator(); iterator.hasNext();)
{
String key = (String) iterator.next();
JSONObject distdata = (JSONObject) jobj.get(key);
JSONObject dists = (JSONObject) distdata.get("districtData");
System.out.println(key);
ArrayList<String> set2 = new ArrayList<String>(dists.keySet());
for(Iterator itr = set2.iterator();itr.hasNext();)
{
String key2 = (String) itr.next();
JSONObject district = (JSONObject) dists.get(key2);
System.out.println(key2);
System.out.println(district);
}
System.out.println("************");
}
conn.disconnect();
}
catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
}

Related

Android JSON only OBJECT Fetching with Iteration

I have a json file which contains only objects now i cant able to fetch all the object with iteration as here is no array.
Here is the code : That i have tried in my android studio & JSon Data Screenshot
#Override
protected String doInBackground(String... strings) {
try {
url = new URL("https://api.myjson.com/bins/r7dj6");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line =" ";
while ((line = bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
String fullfile = stringBuffer.toString();
JSONObject jsonObject = new JSONObject(fullfile);
JSONObject jsonObjectchild = jsonObject.getJSONObject("Apartment");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Here is a complete example. Works for me.
HttpURLConnection connection = null;
try {
URL url = new URL("https://api.myjson.com/bins/r7dj6");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder stringBuffer = new StringBuilder();
while ((line = reader.readLine()) != null){
stringBuffer.append(line);
}
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
JSONObject apartmentObject = jsonObject.getJSONObject("Apartment");
Iterator<String> keys = apartmentObject.keys();
while (keys.hasNext()) {
String flatName = keys.next();
JSONObject flat = apartmentObject.getJSONObject(flatName);
String age = flat.getString("age");
String color = flat.getString("color");
String name = flat.getString("name");
String owner = flat.getString("owner");
String partner = flat.getString("partner");
Log.d("Flat", flatName + ": " + age + ", " + color + ", " + name + ", " + owner + ", " + partner);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
You can still iterate:
for (Iterator key=jsonObjectchild.keys();key.hasNext();) {
JSONObject flatName = json.get(key.next());
...
}

How to get a specific json key value from post request response in Android?

I have following response from post request using HttpURLConnection:
Post Request Response:
{
"LatestData": [{
"ExtraData": null,
"ID": 0,
"season": false,
"latest": 0,
"url": "http://www.awebsite.com/images/12.jpg"
}]
}
How to get value of URL? I tried following but Android Studio keeps giving me error:
String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
Android Studio Error:
error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)
could you guys help me obtain the value of url and let me know what libraries i need to import to android studio so getsonObject works ?Thanks
android code:
if (myURLConnection.getResponseCode() == 200) {
br = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "utf-8"));
while (true) {
line = br.readLine();
if (line != null) {
sb.append(line + "\n");
//String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL =sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
mWebView.loadUrl("javascript:MyFunction('" +newURL + "');");
} else {
br.close();
return sb.toString();
}
}
}
You need to convert sb to a JSONObject to access properties:
JSONOjbect jsonResponse = new JSONObject(new String(sb));
and then:
try {
JSONArray jsonArray = jsonResponse.getJSONArray("LatestData");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dataOjbect = jsonArray.getJSONObject(i);
String url = dataOjbect.getString("url");
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(sb);
String url = jsonObject.optJSONArray("LatestData").getJSONObject(0).optString("url");
} catch (JSONException e) {
e.printStackTrace();
}
Try it using loadJSONArray
String url = loadJSONArray(sb)..getJSONObject(0).getString("url");
Your approach should be like this.
try {
List<String> urlist = new ArrayList<>();
JSONObject jsonObject = new JSONObject(sb.toString());
JSONArray jsonArray = jsonObject.getJSONArray("LatestData");
for (int count = 0; count<jsonArray.length(); count++){
JSONObject jsonInner = jsonArray.getJSONObject(count);
String url = jsonInner.getString("url");
//store your url in some list
urlist.add(url);
}
} catch (JSONException e) {
e.printStackTrace();
}
Can you try this :
StringBuilder sb = new StringBuilder();
line = br.readLine();
while(line != null){
sb.append(line);
}
// if it's fail here then this means there is an issue in parsing JSONObject
JSONObject jsonObj = new JSONObject(sb.toString());
JSONArray latestData = jsonObj.getJSONArray("LatestData");
JSONObject jsonObject = latestData.getJSONObject(0);
String url = jsonObject.getString("url");
Also I'm highly recommending to use Retrofit with GSON .. you can follow this article : http://www.vogella.com/tutorials/Retrofit/article.html
use jsonschema2pojo to generate pojo classes for a JSON data

cannot convert Json string to JSONObject or JSONArray

i have created a rest wcf web service and hosted in local iis, the json string is converted with JsonConvert.SerializeObject(object) of Newtonsoft package.
the output of the web service is
"[{\"companyId\":2,\"companyName\":\"A\"},
{\"companyId\":8,\"companyName\":\"B\"}]"
this web service is consume by android apps,
i tried with JSONArray and JSONObject but it keep on throwing exception
org.json.JSONException: Expected literal value at character 2 of
[{\"companyId\":2,\"companyName\":\"A\"},{\"companyId\":8,\"companyName\":\"B\"}]
org.json.JSONException: Expected literal value at character 2 of
"[{\"companyId\":2,\"companyName\":\"A\"},
{\"companyId\":8,\"companyName\":\"B\"}]"
org.json.JSONException: Value [{"companyId":2,"companyName":"A"},
{"companyId":8,"companyName":"B"}] of type java.lang.String cannot be
converted to JSONArray
this is the code in android class
public JSONArray RequestWebService(URL urlToRequest) {
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(RETRIEVE_TIMEOUT);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
String result = getResponseText(in);
//result = result.substring(1, result.length() - 1);
//result = result.replace("/\\/g", "");
JSONArray j = new JSONArray(result);
return j
}
return null;
}
private String getResponseText(InputStream inStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = null;
try{
rd = new BufferedReader(new InputStreamReader(inStream));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
}finally {
if (rd != null) {
rd.close();
}
}
return sb.toString();
}
String response = "Your Response";
try{
JsonArray jAry = new JsonArray(response);
JsonObjct jObj;
for(int i=0;i<jAry.length;i++){
jObj = JAry.getJsonObject(i);
// You can get your string from object jobj and also use it by store it value in arraylist.
}
} catch(Exception e){
}

Concatinating JSON elements using java-json

I have a program that reads in a CSV file and returns a JSON String.
However using JsonArray and JsonObject only yield the last row of results from the file. How do I concat numerous rows of data into a JSON object?
Output
[{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"},{"name":"Other_Renwables","load":"14.3"}]
Code
JSONObject jObject = new JSONObject();
JSONArray jArray = new JSONArray();
int count = 0;
try{
logger.info("\nSending 'GET' request to URL : " + url);
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
int responseCode = response.getStatusLine().getStatusCode();
logger.info("Response Code : " + responseCode);
if (responseCode != 404){
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()))) {
if(reader != null){
//StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
String[] tab = aux.split(",");
if (count > 0){
try {
jObject.put("name", tab[0]);
jObject.put("load", tab[1]);
jArray.put(jObject);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count++;
}
retVal = jArray.toString();
}
}
}
return retVal;
}finally{
httpClient.getConnectionManager().shutdown();
}
You are using same object and over-writing it in your loop.
This instantiation:
JSONObject jObject = new JSONObject();
must be in your loop.
try {
JSONObject jObject = new JSONObject();
jObject.put("name", tab[0]);
jObject.put("load", tab[1]);
jArray.put(jObject);
}

json data fetched from php and store them in an array in java

My JSON array is this:
{"Name_1":1,"Name_2":0,"Name_3":0}
and my code in java for getting the values and store them in a separate array is the following:
int[] operations= new int[3];
String result = "";
InputStream is = null;
StringBuilder sb=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://testteamgr.netau.net/parsing/test.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONObject json_data = new JSONObject(result);
System.out.println("Length of json is"+jArray.length());
for(int i=0;i<jArray.length();i++){
if (i==0) operations[0]=json_data.getInt("Name_1");
else if (i==1) operations[1]=json_data.getInt("Name_2");
else if (i==2) operations[2]=json_data.getInt("Name_3"); }
and I am getting those errors:
value br of type java.lang.string cannot be converted to jsonobject
If I print out the result I do not see the JSONobject but the html code.
So what I want is to get these 3 values into a separate array.
You have an object, not an array. To process the result you can use following code:
String json = "{\"Name_1\":1,\"Name_2\":0,\"Name_3\":0}";
JSONObject object = new JSONObject(json);
String[] propertyNames = JSONObject.getNames(object);
String[] values = new String[propertyNames.length];
for (int i = 0; i < propertyNames.length; i++) {
values[i] = String.valueOf(object.get(propertyNames[i]));
}

Categories