Parse JSON File with coordinates in Android - java

I'm new to Java and having problems with parsing json. I have a json file in res folder and need to get lat/lng from the file which will be displayed with a marker later. How can I parse the file within public void without needing to create a new Java Class or Activity?
Json
{
"type":"FeatureCollection",
"crs":{
"type":"name",
"properties":{
"name":"urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features":[
{
"type":"Feature",
"properties":{
"MEAN_X":13.34994,
"MEAN_Y":52.54291,
"UID":"B154"
},
"geometry":{
"type":"Point",
"coordinates":[
13.34993674,
52.54291394
]
}
},
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
JSONObject jsonObj = new JSONObject(R.raw.level1_points);
final String TAG_FEATURES = jsonObj.getString("features");
final String TAG_PROPERTIES = jsonObj.getString("properties");
final double TAG_MEANX = jsonObj.getDouble("MEAN_X");
final double TAG_MEANY = jsonObj.getDouble("MEAN_X");
final String TAG_UID = jsonObj.getString("UID");
try {
JSONArray features = jsonObj.getJSONArray(TAG_FEATURES);
for (int i = 0; i < features.length(); i++) {
// Create a marker for each room in the JSON data.
JSONObject c = features.getJSONObject(i);
JSONObject properties = c.getJSONObject(TAG_PROPERTIES);
Double MEAN_X = properties.getDouble(TAG_MEANX);
Double MEAN_Y = properties.getDouble(TAG_MEANY);
String UID = properties.getString(TAG_UID);
if (spinner.getSelectedItem().toString().equals(UID)) {
LatLng room = new LatLng(MEAN_X; MEAN_Y);
mMap.addMarker(new MarkerOptions().position(raum).title("Room"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(room));
mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
<code>

you can do the following changes
first you'll have to get the json file from the res folder
and then parse the json data
// get the json file
InputStream inputStream = getResources().openRawResource(R.raw.level1_points);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
String jsonString = byteArrayOutputStream.toString();
Log.v("Text Data", jsonString);
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray features = jsonObj.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
// Create a marker for each room in the JSON data.
JSONObject c = features.getJSONObject(i);
JSONObject properties = c.getJSONObject("properties");
Double MEAN_X = properties.getDouble("MEAN_X");
Double MEAN_Y = properties.getDouble("MEAN_Y");
String UID = properties.getString("UID");
Log.e(TAG, "onCreate: " + MEAN_X + MEAN_Y + UID);
}
} catch (Exception e) {
Log.e(TAG, "onCreate: " + e.getMessage());
}

Related

Parsing another JSON Format

So here's the following code :
jObj = new JSONObject(valeurARenvoyer);
hauteur = jObj.getString("niveauEau");
debit = jObj.getString("debit");
date = jObj.getString("dateReleve");
batterie = jObj.getString("chargeBatterie");
presence = jObj.getString("etatPerimetrique");
bat = jObj.getString("chargeBatterie");
So i used this code to parse a JSON which was like that :
{"id":"15","id_Station":"Artiguelouve","Date_Releve":"2017-02-16 16:07:41","Niveau_Eau":"29","Charge_Batterie":"9","Etat_Perimetrique":"0","Debit":"13.35"}
It worked well, but now my JSON response looks like that :
{"Station":"Artiguelouve","debit":[{"niveauEau":0,"debit":32.5,"dateReleve":{"date":"2017-06-08 15:59:03","timezone_type":3,"timezone":"Europe\/Paris"},"idStation":"Artiguelouve","etatPerimetrique":true,"chargeBatterie":14590}]}
With this response i can't find how to parse this.
valeurARenvoyer is my JSON. Can you have any solution to do that please ?
add this code to get response
JSONObject jsonObject = new JSONObject(jsonResponse);//put your json response
JSONArray jsonArray = null;
try {
String station = jsonObject.getString("Station");
jsonArray = jsonObject.getJSONArray("debit");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
int niveauEau = jsonObject1.getInt("niveauEau");
int debit = jsonObject1.getInt("debit");
String isStation = jsonObject1.getString("idStation");
boolean etatPerimetrique = jsonObject1.getBoolean("etatPerimetrique");
int chargeBatterie = jsonObject1.getInt("chargeBatterie");
JSONObject jsonObject2 = jsonObject1.getJSONObject("dateReleve");
String date = jsonObject2.getString("date");
int timezone_type = jsonObject2.getInt("timezone_type");
String timezone = jsonObject2.getString("timezone");
}
} catch (JSONException e) {
e.printStackTrace();
}
try this code
try {
JSONObject jsonObject = new JSONObject(valeurARenvoyer);
JSONArray jsonArray = jsonObject.getJSONArray("debit");
for(int i = 0; i < jsonArray.length(); i++){
// you can get niveauEau, debit, idStation, etatPerimetrique,
// chargeBatterie, dateReleve JsonObject values in this loop
}
} catch (JSONException e) {
e.printStackTrace();
}

How to get some elements in nested JSON objects in a JSON array

I hava this JSON:
[
{
"title": "This a Sample title for each post_title",
"excerpt": "And this is a sample of the post_body,
"author": "King Spark",
"featured_picture": {
"source": "https://exapmple.com/blah/blah/image.jpg",
"year": "2015",
"ownwer": "Akim Man",
},
},...
From the json I only need the title, excerpt elements of the main objects. Then from the featured_picture objects, I want only the source element.
I have written this code and it seems not to be working:
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_pocture object
for (int f = 0; f<array.length(); f++) {
JSONObject object = array.getJSONObject(f);
JSONObject postImage = object.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
}
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
mPostItemsList.add(postItem);
}
}
Try to parse the nested JSON like this way:
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_picture object
JSONObject postImage = jsonObject.getJSONObject("featured_picture");
postItem.setPost_image(postImage.getString("source"));
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}
mPostItemsList.add(postItem);
}
}
You won't continue read the array here
for (int f = 0; f<array.length(); f++) {
featured_picture is an entry in the map and returns a map too.
The acces should be like this :
array.getJSONObject(i).getJSONObject("featured_picture").getString("source");
You have to identify object and array in json then find value by key, once you learnt then complexity of json doesn't matter to parse follow tutorial
your code for (int f = 0; f<array.length(); f++) {
JSONObject object = array.getJSONObject(f);
JSONObject postImage = object.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
}
is not correct, this part of json is not an array but an object inside another jsonObject.
Here no need to iterate loop to read nested JSONobject.
Because "featured_picture" gives only JSONObject not an array. In case if its return array you should read like this:
JSONObject rootObject=new JSONObject();
JSONArray nestedObject=rootObject.getJSONArray("key");
Here i modified your code in correct manner hope will it help for you.
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
//Parsing featured_pocture object
JSONObject postImage = jsonObject.getJSONObject("featured_picture");
String imageURL = postImage.getString("source");
postItem.setPost_image(imageURL);
} catch (JSONException w) {
w.printStackTrace();
//Toast.makeText(this, "Error in parsing Json", Toast.LENGTH_LONG).show();
}

getJSONArray() in GraphResponse Cannot be applied to java.lang.String - Facebook

i have develop a android application integrate with facebook login now i want to make facebook app invite function(invitable_friends api) but in my code i got red underline errors.
private void loadFriendsFromFacebook(final String str) {
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
new GraphRequest(AccessToken.getCurrentAccessToken(), str, null, HttpMethod.GET,
new GraphRequest.Callback() {
List<String> s = new ArrayList();
List<String> F = new ArrayList();
List<String> G = new ArrayList();
String t = "";
String u = "";
int w = 0;
boolean x = false;
String[] y = new String[2];
String E = "";
OnInviteListener onInviteListener = null;
public void onCompleted(GraphResponse response) {
SharedPreferences.Editor edit = getSharedPreferences("friendsData", 0).edit();
try {
int i;
JSONArray jSONArray = response.getJSONArray("data");
for (i = 0; i < jSONArray.length(); i++) {
this.s.add(jSONArray.getJSONObject(i).getString(Page.Properties.ID));
}
for (i = 0; i < jSONArray.length(); i++) {
this.G.add(jSONArray.getJSONObject(i).getJSONObject(Page.Properties.PICTURE).getJSONObject("data").getString("url"));
edit.putString("friendPhoto", jSONArray.getJSONObject(i).getJSONObject(Page.Properties.PICTURE).getJSONObject("data").getString("url"));
this.F.add(jSONArray.getJSONObject(i).getString(Page.Properties.NAME));
edit.putString("friendName", jSONArray.getJSONObject(i).getString(Page.Properties.NAME));
}
edit.commit();
for (i = 0; i < this.s.size(); i++) {
this.u += ((String) this.s.get(i)) + ",";
}
JSONObject jSONObject2 = response.getJSONObject("paging");
if (jSONObject2.toString().contains("next")) {
this.t = jSONObject2.getString("next").toString();
} else if (this.s.size() < 1) {
this.x = true;
}
} catch (Exception e) {
System.out.println("Exception=" + e);
e.printStackTrace();
}
}
}).executeAsync();
}
where the response.getJSONArray("data");
data is underline red which is click rover shows getJSONArray() in graphrespone cannot be applied to java.lang.sting..
and same error in the response.getJSONObject("paging");
Can anyone please tell me what is wrong in the code?
it will be appreciated..
From here (https://developers.facebook.com/docs/reference/android/current/class/GraphResponse/) I can see that getJSONObject() and getJSONArray() do not have parameters at all. You should retrieve the object respective the array from the GraphResponse using this methods and once you have a JsonObject or JsonArray you can access specific fields.
response.getJSONArray() will give you an object of type JSONArray and response.getJSONObject() will give you an object of type JSONObject. Using this objects you can access the fields using jsonObject.getString("user_id") or similar (see docs.oracle.com/javaee/7/api/javax/json/JsonObject.html)

How to read json with this format

how can i read this JSON format,and user can pass the from and to into URL,
and want to print these from_amount and to_amount into the text view on button click.
api url
{
"from": "INR",
"to": "GBP",
"from_amount": 2,
"to_amount": 0.019798718798321
}
i tried to do the snippet below.,but it is not returning any thing and also not giving any error in thr log cat
private static final String API_URL = "http://devel.farebookings.com/api/curconversor/t1/t2/usds/json";
if (!usdValue.getText().toString().equals("")) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(API_URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.i("CHACHING", "HTTP Sucess");
try {
JSONObject jsonObj = new JSONObject(response);
JSONObject ratesObject = jsonObj
.getJSONObject("from");
JSONObject ratessObject = jsonObj
.getJSONObject("to");
JSONObject rates2Object = jsonObj
.getJSONObject("from_amount");
//Double RateTo = Double.valueOf(t2
// .toString());
Double RateFrom = Double.valueOf(t1
.toString());
// Double RateFrom = ratesObject.getDouble("from");
//Double RateTo = ratesObject.getDouble(t2.toString());
//Log.i("CHACHING", "GBP: " + gbpRate);
//Log.i("CHACHING", "EUR: " + eurRate);
Double usds = Double.valueOf(usdValue.getText()
.toString());
//Double gbps = usds * RateFrom;
// Double euros = usds * RateTo;
//Result.setText("ConvertedFrom: "
// + String.valueOf(RateFrom)+ "ConvertedTo: "
// + String.valueOf(RateTo));
Toast.makeText(getApplicationContext(),
Result.getText().toString(), Toast.LENGTH_LONG)
.show();
//ConvertedTo.setText("ConvertedTo: "
//+ String.valueOf(RateTo));
}
Don't use the getJsonObject() method to get the values inside the JSONObject, but use the corresponding getters for the types of the values. The key-value pairs themselves are no JSONObjects.
JSONObject jsonObj = new JSONObject(response);
String fromCurrency = jsonObj.getString("from");
String toCurrency= jsonObj.getJSONObject("to");
Double fromAmount = jsonObj.getDouble("from_amount");
Double toAmount= jsonObj.getDouble("to_amount");

How do you parse JSON with a colon in the name? Android/Java

For example: { "primary:title":"Little Red Riding Hood"}
My Parser in Java (Android) is always getting stuck because of the colon between primary and title. I can parse anything else with ease, I just need help in this.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView txtViewParsedValue;
private JSONObject jsonObject;
private JSONArray jsonArray;
String [] titles, links, mediaDescriptions, mediaCredits, descriptions, dcCreators, pubDates, categories;
String [] permalinks, texts; // guid
String [] rels, hrefs;
String [] urls, media, heights, widths; // media:content
String strParsedValue = "";
private String strJSONValue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
strJSONValue = readRawTextFile(this, R.raw.jsonextract);
txtViewParsedValue = (TextView) findViewById(R.id.text_view_1);
try {
parseJSON();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseJSON() throws JSONException
{
txtViewParsedValue.setText("Parse 1");
jsonObject = new JSONObject(strJSONValue);
jsonArray = jsonObject.getJSONArray("item");
titles = new String[jsonArray.length()];
links = new String[jsonArray.length()];
permalinks = new String[jsonArray.length()];
texts = new String[jsonArray.length()];
mediaDescriptions = new String[jsonArray.length()];
mediaCredits = new String[jsonArray.length()];
descriptions = new String[jsonArray.length()];
dcCreators = new String[jsonArray.length()];
pubDates = new String[jsonArray.length()];
categories = new String[jsonArray.length()];
txtViewParsedValue.setText("Parse 2");
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
titles[i] = object.getString("title");
links[i] = object.getString("link");
JSONObject guidObj = object.getJSONObject("guid");
permalinks[i] = guidObj.getString("isPermaLink");
texts[i] = guidObj.getString("text");
//mediaDescriptions[i] = object.getString("media:description");
//mediaCredits[i] = object.getString("media:credit");
// *** THE PARSER FAILS IF THE COMMENTED LINES ARE IMPLEMENTED BECAUSE
// OF THE : IN BETWEEN THE NAMES ***
descriptions[i] = object.getString("description");
//dcCreators[i] = object.getString("dc:creator");
pubDates[i] = object.getString("pubDate");
categories[i] = object.getString("category");
}
for (int i=0; i<jsonArray.length(); i++)
{
strParsedValue += "\nTitle: " + titles[i];
strParsedValue += "\nLink: " + links[i];
strParsedValue += "\nPermalink: " + permalinks[i];
strParsedValue += "\nText: " + texts[i];
strParsedValue += "\nMedia Description: " + mediaDescriptions[i];
strParsedValue += "\nMedia Credit: " + mediaCredits[i];
strParsedValue += "\nDescription: " + descriptions[i];
strParsedValue += "\nDC Creator: " + dcCreators[i];
strParsedValue += "\nPublication Date: " + pubDates[i];
strParsedValue += "\nCategory: " + categories[i];
strParsedValue += "\n";
}
txtViewParsedValue.setText(strParsedValue);
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
For one, and to answer your question, there is no issue with JSONObject and the org.json.* classes parsing keys with colons in them if they're properly formed. The following unit test passed which means it was able to parse your example scenario:
public void testParsingKeysWithColons() throws JSONException {
String raw = "{ \"primary:title\":\"Little Red Riding Hood\"}";
JSONObject obj = new JSONObject(raw);
String primaryTitle = obj.getString("primary:title");
assertEquals("Little Red Riding Hood", primaryTitle);
}
Another suggestion is that using arrays of Strings for your data is clumsy and you'd be much better organized using a data structure to represent your objects. Instead of string arrays for titles, links, descriptions; use an object that has these properties and make a list of the objects. For example:
public class MyDataStructure {
public String title;
public String primaryTitle;
public String link;
public String mediaDescription;
public static class Keys {
public static String title = "title";
public static String primaryTitle = "primary:title";
public static String link = "link";
public static String mediaDescription = "media:description";
}
}
And then you can make a "translator" class that does all the parsing for you and returns a list of your object. This is much easier to work with and keep track of. You never have to think about data misaligning or having more or less data in one of your arrays than you expected. You also have a much easier time testing where the problem is if your input data is missing anything or any of your json is malformed.
public class MyDataStructureTranslator {
public static List<MyDataStructure> parseJson(String rawJsonData) throws JSONException {
List<MyDataStructure> list = new ArrayList<MyDataStructure>();
JSONObject obj = new JSONObject(rawJsonData);
JSONArray arr = obj.getJSONArray("item");
for(int i = 0; i < arr.length(); i++) {
JSONObject current = arr.getJSONObject(i);
MyDataStructure item = new MyDataStructure();
item.title = current.getString(MyDataStructure.Keys.title);
item.primaryTitle = current.getString(MyDataStructure.Keys.primaryTitle);
item.link = current.getString(MyDataStructure.Keys.link);
item.mediaDescription = current.getString(MyDataStructure.Keys.mediaDescription);
list.add(item);
}
return list;
}
}
Since Java identifiers cannot have colons, just specify a json property name that maps to the exact json name like:
#JsonProperty("primary:title")
public String primaryTitle;

Categories

Resources