How can I extract a specific part of a JSON file? - java

This is my JSON file :
{
"coord":{
"lon":139,
"lat":35
},
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F04n.png?1499366020983"
}
],
"base":"stations",
"main":{
"temp":7,
"pressure":1025,
"humidity":75,
"temp_min":7,
"temp_max":7
},
"visibility":10000,
"wind":{
"speed":5.1,
"deg":100
},
"clouds":{
"all":75
},
"dt":1549794600,
"sys":{
"type":1,
"id":8024,
"message":0.0034,
"country":"JP",
"sunrise":1549748122,
"sunset":1549786891
},
"id":1851632,
"name":"Shuzenji",
"cod":200
}
I have tried to extract the weather array but it doesn't work.
JSONArray mArray;
try {
mArray = new JSONArray(result);
for (int i = 0; i < mArray.length(); i++) {
JSONObject mJsonObject = mArray.getJSONObject(i);
txtJson.append(mJsonObject.getString("weather"));
}
} catch (JSONException e) {
e.printStackTrace();
//txtJson.setText(result);
}
txtJson.setText(result);
}

I don't know what you expect that code to do, but if you want to extract the weather array, this is how you do it.
JSONObject json = new JSONObject(result);
JSONArray weather = json.getJSONArray("weather");
Then you can get individual entries in the array
JSONObject entry = weather.getJSONObject(0);
int id = entry.getInt("id");
String main = entry.getString("main");
or if you just want to turn the array back to a string
String s = weather.toString();

Related

Parse 2d Json in java [duplicate]

This question already has answers here:
How to parse JSON 2D array using Java
(2 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Trying to parse this type of json format in java
{
"output": "success",
"result": [
{
"id": 1,
"label": "name",
},
{
"id": 2,
"label": "name_2",
}
]
}
I am getting this type of json format, now what i want to do is check first if output.equalsIgnoreCase("success)" if true then parse the second array of result.
And this is i tried so far.
try {
JSONArray myJson = new JSONArray(response);
String status = myJson.getString(Integer.parseInt("output"));
if(status.equalsIgnoreCase("success")) {
for (int i = 0; i < myJson.length(); i++) {
JSONObject obj = myJson.getJSONObject(i);
name.add(obj.getString("label"));
}
Log.e("list" , name.toString());
}
} catch (Exception e) {
}
String responceStr = ...; // here is your full responce string
try {
JSONObject responce = new JSONObject(responceStr);
String status = responce.getString("output");
if ("success".equalsIgnoreCase(status)) {
JSONArray result = responce.getJSONArray("result");
for (int i=0; i < result.length(); i++){
JSONObject jsonPair = result.getJSONObject(i);
int id = jsonPair.getInt("id");
String label = jsonPair.getString("label");
}
}
} catch (JSONException e){
}
Integer.parseInt("123") -- is OK.
Integer.parseInt("output") -- is NOT OK.
because Integer.parseInt() parses the string representation of an integer. "output" string does not represent an integer.
The response is a JSONObject, not JSONArray (it is enclosed between curly brackets). The array is the field named result.
So change myJson to JSONObject and after checking the success field,
create a new variable
JSONArray resultArray = myJson.getArray("result");
and iterate over this instead of myJson. Also you should not discard the exception since the stacktrace could provide some hint about the problems. You can add
e.printStackTrace();
in the catch block.

How to Parse JSON Data like array-->Object-->Object with value

I'm New to android development. I just know very little about JSON. I used Json simple format.
{
"worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
},
{
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":"http://www.androidbegin.com/tutorial/flag/india.png"
}
]
}
In above JSON data we can simply call rank, country after getting JSOn array worldpopulation.
Now I have JSON data showed below, here JSON array is same I think since item is present I don't know. Then it has objects as numbers under that it has country.
{
"Items":"0 to 2",
"worldpopulation":[
{
"0":{
"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
}
},
{
"1":{
"country":"India",
"population":"1,210,193,422",
"flag":"http://www.androidbegin.com/tutorial/flag/india.png"
}
}
]
}
Now I don't know how to call country, population and flag.
Is it same method as. Jsonobject.getstring("rank"); after jsonarray("worldpopulation");
Or different.
Do as following
try {
JSONObject reader = new JSONObject("your json str");
JSONArray items = reader.getJSONArray("worldpopulation");
for (int i = 0; i < items.length(); ++i) {
JSONObject jsonProgram = items.getJSONObject(i);
JSONObject yourObject = null;
if (i == 0) {
yourObject = jsonProgram.getJSONObject("0");
} else {
yourObject = jsonProgram.getJSONObject("1");
}
//Do here what did before with yourObject
}
} catch (JSONException e) {
Log.i("Test", e.toString());
}

get data from Json array in Json array Android Java

Hello how to get data from Json Array in another Json array i have get data till attachments but attachment doesnt work, All code work till attachments how to get data from attachments I need to get "photo_75" from it
Json
"response":{
"count":3,
"items":[
{
"id":3,
"from_id":205110032,
"owner_id":-81865402,
"date":1417672154,
"post_type":"post",
"text":"jjjjASDFGHJKYTRDXCVB",
"attachments":[
{
"type":"photo",
"photo":{
"id":330414711,
"album_id":-7,
"owner_id":205110032,
"photo_75":"http:\/\/cs605116.vk.me\/v605116032\/6325\/3SwTo8j4lJ0.jpg",
"photo_130":"http:\/\/cs605116.vk.me\/v605116032\/6326\/_OZA86FO3Nw.jpg",
"photo_604":"http:\/\/cs605116.vk.me\/v605116032\/6327\/AUtB59708Nw.jpg",
"photo_807":"http:\/\/cs605116.vk.me\/v605116032\/6328\/59oAdfz9jgI.jpg",
"width":538,
"height":807,
"text":"",
"date":1399134687,
"access_key":"7297eb663de2e4e6b2"
}
}
],
"comments":{
"count":0
},
"likes":{
"count":0
},
"reposts":{
"count":0
}
},
Java
private void parseJsonFeed(JSONObject response) {
try {
JSONObject parent = response.getJSONObject("response");
JSONArray feedArray = parent.getJSONArray("items");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("post_type"));
item.setTimeStamp(feedObj.getString("date"));
// Image might be null sometimes
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
item.setStatus(feedObj.getString("text"));
All code work till there how to get data from attachments
***JSONObject response1 = response.getJSONObject("response");
feedArray = parent.getJSONArray("items");***
JSONArray feedArray1 = response1.getJSONArray("attachments");
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject feedObj1 = (JSONObject) feedArray1.get(i1);
FeedItem item1 = new FeedItem();
item.setProfilePic(feedObj1.getString("photo_75"));
}
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance
you are looking for attachments in wrong object. "attachmetnts" is property of item.
instead of
JSONArray feedArray1 = response1.getJSONArray("attachments");
use
JSONArray feedArray1 = feedObj.getJSONArray("attachments");
in your case feedObj contains item object.
to get photo :
Remove lines :
String image = feedObj.isNull("photo") ? null : feedObj
.getString("photo");
item.setImge(image);
and change it to :
for (int i1 = 0; i1 < feedArray1.length(); i1++) {
JSONObject attachment = (JSONObject) feedArray1.get(i1);
JSONObject photo = (JSONObject) attachment.getJSONObject("photo");
item.setImge(photo);
item.setProfilePic(photo.getString("photo_75"));
item.setStatus(photo.getString("text"));
}
You can try GSON, which would directly give you a java object from your json and you would not have to parse it manually.

JSON parse Android - object in object

How to parse this json? I want get data from title, field_place and brothers fields.
{
"events": [
{
"event": {
"title": "BITUMIX Martyna Jastrz\u0119bska",
"field_place": "Nowe Miejsce Al Jerozolimskie 51 lok.2",
"field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/martyna_jastrzebska_bitumix_2.jpg?itok=nd2O5U5z"
}
},
{
"event": {
"title": "Wiecz\u00f3r Komedii Improwizowanej - D\u017cem Impro!",
"field_place": "",
"field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/dzem_17_maja.jpg?itok=bfgDYxKq"
}
},
...
I tried:
JSONObject itemm = jArray.getJSONObject(i);
JSONObject oneObject = itemm.getJSONObject("event");
String title = oneObject.getString("title");
String field_place = oneObject.getString("field_place");
... but it doesn't work.
In a JSON string , there are two symbols that guide you through parsing :
{ - indicates a JSONObject
[ - indicates a JSONArray
When parsing a json string, you should go through this items iteratively. To understand how many JsonObjects and JsonArrays you have in your string , and from which you should start parsing, use a json-visualizer tool like this website. :
Example : As you see, the root object is a JSONObject which consists of an JSONArray with three jsonOnjects. To parse such a structure you can use :
JSONObject jsonobj = new JSONObject(jsonstring);
String result = jsonObject.getString("success");
String error_number = jsonObject.getString("error_number");
String error_message = jsonObject.getString("error_message");
JSON Array jsonarray = jsonobj.getJSONArray();
String[] names = new String[jsonArray.length()];
String[] formattedNames = new String[jsonArray.length()];
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
names [i] = jsonObject.getString("name");
formattedNames [i] = jsonObject.getString("formattedName");
}
try this
JSONArray element = jsonobj.getJSONArray("events");
for(int i=0;i < element.length();i++){
JSONObject e = element.getJSONObject(i);
Log.d("TESTTT22",e.getJSONObject("event").getString("title"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to convert JSON formatted string of data rows of a table in to java array in android

I have a JSON string like this of data for a table in an android app. one of {} is a row of data for the table. I want to separate these {}s into an array and then each element inside this array into other sub-arrays separating other elements inside {}. Please suggest an appropriate way of accomplishing this criteria using JSON. Thank you.
[
{
"nodeName":"prime_mtsc22#smpp3",
"nodeId":"MTSC3",
"tidPrefix":"4",
"optStatus":"offline",
"daStart":"1",
"daEnd":"3",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp2",
"nodeId":"MTSC58",
"tidPrefix":"1",
"optStatus":"blocked",
"daStart":"5",
"daEnd":"10",
"description":"new description"
},
{
"nodeName":"prime_mtsc22#smpp1",
"nodeId":"MTSC1",
"tidPrefix":"15",
"optStatus":"online",
"daStart":"12",
"daEnd":"20",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp0",
"nodeId":"MTSC15",
"tidPrefix":"15",
"optStatus":"offline",
"daStart":"25",
"daEnd":"30",
"description":"Description"
}
]
ok so in that case the code to use is this
String jsonString = <your jsonString>;
// THIS IS NOT NEEDED ANYMORE
//JSONObject json = new JSONObject(jsonString);
JSONArray topArray = null;
try {
// Getting your top array
// THIS IS NOT NEEDED ANYMORE
//topArray = json.getJSONArray(jsonString);
//use this instead
topArray = new JSONArray(jsonString);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
ok?
Use JSONObject for this http://developer.android.com/reference/org/json/JSONObject.html
Example
String jsonString = <your jsonString>;
JSONObject json = new JSONObject(jsonString);
JSONObject topArray = ;
try {
// Getting your top array
topArray = json.getJSONArray(TAG_ARRAY_TOP);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
Use the NodePOJO class to hold each row values.
public class NodePOJO {
private String nodeName;
// do for rest of the json row data
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public String getNodeName() {
return this.nodeName;
}
}

Categories

Resources