Not able to get JSONObject in to JSONArray IN JAVA eclipes - arrays

I was not able to get JsonObject while I try to covert JsonObject to JsonArray
JSON DATA:
{
"in”: [
{
"Action": "In",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
},
{
"Action": "OUT",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
},
{
"Action": "In",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
}
],
"click": [
{
"Action": "Click",
"namespace": "Zdesk",
"InDate": "Sep 27, 2019"
},
{
"Action": "Click",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
},
{
"Action": "Click",
"namespace": "Zdesk",
"InDate": "Nov 4, 2019"
}
]
}
and I use the below code to get those objects using the "Get" method
how to get "click" objects alone,
i tried below code
URL url = new URL("https://localdummy.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
and get those details in "inline"
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+=sc.nextLine();
}
System.out.println(inline);
sc.close();
}
Then got those object into array
JSONObject jobj = new JSONObject (inline);
JSONArray jsonarr_1 = (JSONArray) jobj.get("in"); //its working
//JSONArray jsonarr_1 = (JSONArray) jobj.get("click"); <- <- <- <-//its not working . i need to use this ((((its issues))))
please help me to get jobj in to jsonarr_1 for get "click"
Thanks in advance

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class Demo{
public static void main(String[] args) {
String resp = "{\"in\":[{\"Action\":\"In\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"},{\"Action\":\"OUT\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"},{\"Action\":\"In\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"}],\"click\":[{\"Action\":\"Click\",\"namespace\":\"Zdesk\",\"InDate\":\"Sep27,2019\"},{\"Action\":\"Click\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"},{\"Action\":\"Click\",\"namespace\":\"Zdesk\",\"InDate\":\"Nov4,2019\"}]}";
JSONObject jsonObject = JSONObject.parseObject(resp);
JSONArray click = jsonObject.getJSONArray("click");
System.out.println(click);
}
}
you will get what you want:
[{"Action":"Click","InDate":"Sep 27, 2019","namespace":"Zdesk"},{"Action":"Click","InDate":"Nov 4, 2019","namespace":"Zdesk"},{"Action":"Click","InDate":"Nov 4, 2019","namespace":"Zdesk"}]
hope to help you

Related

Problems parsing complex json in Flutter

I am having issues converting the following response ->
{
"data": [
{
"_id": "1AoJoWJ5Hdx3nZ5t",
"title": "Orange is the new black",
"imageUrl": "/1532353304050-oinb.jpg",
"likesCount": 674
},
{
"_id": "AeqiQJewtTvMPc1B",
"title": "X-Files",
"imageUrl": "/1532353346638-xfiles.png",
"likesCount": 6155
},
{
"_id": "gPkzfXoJXX5TuTuM",
"title": "Star Trek: Voyager",
"imageUrl": "/1532353336145-voyager.jpg",
"likesCount": 23
},
{
"_id": "vQBQcYwtF9GWWJyK",
"title": "South Park",
"imageUrl": "/1532353313669-southpark.jpg",
"likesCount": 56
},
{
"_id": "wjLUixBQ4sirMAYw",
"title": "The Simpsons",
"imageUrl": "/1532353326075-thesimpsons.jpg",
"likesCount": 65
}
]
}
I tried using the jsonserializer plugin as well as the json_annotations plugin but got nowhere.
I did try to get a parser class with quicktype.io but It seems to not work at all.
Can someone please guide me or assist me with this issue?
Thanks!
There is a good plugin for that in Android Studio.
JSON to Dart Class.
Once you install the plugin do as follow.
Press ALT + L
Give a Class Name and paste your JSON response
And you are done.
After you get a response do as follow as
import 'dart:convert';
var decodedData = json.decode(response.body);
var data = Data.fromJson(decodedData)
If you need the status code of you response then response.statusCode
I followed this official document of Flutter and it works for me.
https://flutter.dev/docs/development/data-and-backend/json
Follow these steps to solve your problem.
Add dependencies as shown in the document.
dependencies:
# Your other regular dependencies here
json_annotation: <latest_version>
dev_dependencies:
# Your other dev_dependencies here
build_runner: <latest_version>
json_serializable: <latest_version>
Create stackoverflow.dart
import 'package:json_annotation/json_annotation.dart';
part 'stackoverflow.g.dart';
#JsonSerializable()
class StackOverFlowModel {
#JsonKey(name: '_id')
String id;
String title;
String imageUrl;
int likesCount;
StackOverFlowModel();
factory StackOverFlowModel.fromJson(Map<String, dynamic> json) =>
_$StackOverFlowModelFromJson(json);
Map<String, dynamic> toJson() => _$StackOverFlowModelToJson(this);
}
Giving variable name as _id will confuse Dart with a private variable. It is better to give it a JSON name using JsonKey annotation.
Run flutter pub run build_runner build in the terminal.
stackoverflow.g.dart will be generated like this.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'stackoverflow.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
StackOverFlowModel _$StackOverFlowModelFromJson(Map<String, dynamic> json) {
return StackOverFlowModel()
..id = json['_id'] as String
..title = json['title'] as String
..imageUrl = json['imageUrl'] as String
..likesCount = json['likesCount'] as int;
}
Map<String, dynamic> _$StackOverFlowModelToJson(StackOverFlowModel instance) =>
<String, dynamic>{
'_id': instance.id,
'title': instance.title,
'imageUrl': instance.imageUrl,
'likesCount': instance.likesCount
};
For testing do this
Map map = {
"data": [
{
"_id": "1AoJoWJ5Hdx3nZ5t",
"title": "Orange is the new black",
"imageUrl": "/1532353304050-oinb.jpg",
"likesCount": 674
},
{
"_id": "AeqiQJewtTvMPc1B",
"title": "X-Files",
"imageUrl": "/1532353346638-xfiles.png",
"likesCount": 6155
},
{
"_id": "gPkzfXoJXX5TuTuM",
"title": "Star Trek: Voyager",
"imageUrl": "/1532353336145-voyager.jpg",
"likesCount": 23
},
{
"_id": "vQBQcYwtF9GWWJyK",
"title": "South Park",
"imageUrl": "/1532353313669-southpark.jpg",
"likesCount": 56
},
{
"_id": "wjLUixBQ4sirMAYw",
"title": "The Simpsons",
"imageUrl": "/1532353326075-thesimpsons.jpg",
"likesCount": 65
}
]
};
List<StackOverFlowModel> list = List.generate(map['data'].length,
(index) => StackOverFlowModel.fromJson(map['data'][index]));
print(list);

Swift - Use dictionary to pass data to params

I'm trying to pass some datas in my parameters to send to a server. But I'm facing some difficulties to build the params.
I have tried to loop through the array to add the dictionary which consists of the mobile and name but I'm not sure on how to build it properly as it return only first element of the array. I don't know how to append everything in the array.
var parameters: [String: Any] = ["invitations": [
["mobile": "1234567",
"name": "John1"]
]
]
for (item1, item2) in zip(arrName, arrNumber){
parameters = ["invitations": [
"mobile" : "\(item2)",
"name" : "\(item1)"]
]
}
This is the JSON I'm trying to build in the params.
{
"invitations": [
{
"mobile": "1234456",
"name": "Paul"
},
{
"mobile": "1234456",
"name": "Paul1"
},
{
"mobile": "1234456",
"name": "Paul2"
}
]
}
let arr = zip(arrNumber,arrName).map { ["mobile":$0,"name":$1] }
var parameters: [String: Any] = ["invitations": arr]
print(parameters)//["invitations": [["name": "Paul", "mobile": "1234456"], ["name": "Paul1", "mobile": "1234456"], ["name": "Paul2", "mobile": "1234456"]]]
do {
let json = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
let convertedString = String(data: json, encoding: .utf8)
print(convertedString)
} catch let error {
print(error.localizedDescription)
}
{ "invitations": [
{
"name": "Paul",
"mobile": "1234456"
},
{
"name": "Paul1",
"mobile": "1234456"
},
{
"name": "Paul2",
"mobile": "1234456"
} ] }

Openweathermap API Forecast accessing array

So I'm trying to mess around with the openweathermap API and I can't figure out how to access some of the data.
Here the snippet of code I have that access the API.
public void find_forecast () {
String url = "http://api.openweathermap.org/data/2.5/forecast?id=4466033&appid=e4c641dd837c7947a127972091185dad&units=imperial";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("list");
JSONObject object = array.getJSONObject(1);
String description = object.getString("dt");
day1.setText(description);
Here is a snippet of the API code:
{
"cod": "200",
"message": 0.0042,
"cnt": 40,
"list": [
{
"dt": 1524614400,
"main": {
"temp": 63.77,
"temp_min": 63.77,
"temp_max": 64.26,
"pressure": 1017.45,
"sea_level": 1021.4,
"grnd_level": 1017.45,
"humidity": 97,
"temp_kf": -0.27
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
So as you can see the code above will return the value of dt which is 1524614400. But I'm trying to access for example under "weather" the "description" which in this case is light rain. I guess I don't know how to access an array inside an array, although I couldn't even get the "temp" to return under "main", although I could get "main" to return everything underneath it.
Thanks for any help.
Max
Not sure about Android but in Javascript I would try this:
var dataObj = {
"cod": "200",
"message": 0.0042,
"cnt": 40,
"list": [
{
"dt": 1524614400,
"main": {
"temp": 63.77,
"temp_min": 63.77,
"temp_max": 64.26,
"pressure": 1017.45,
"sea_level": 1021.4,
"grnd_level": 1017.45,
"humidity": 97,
"temp_kf": -0.27
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
]
}
]
}
console.log(dataObj.list[0].weather[0].description);
I finally figured this out. Code is below!
String array = response.getJSONArray("list").getJSONObject(0).getJSONArray("weather").getJSONObject(0).getString("description");
day1.setText(array);
This will return light rain from the API code above.

Get nested JSON object from a JSON Array

May i know how to get JSON object from an json array??
JSON:
[
{
"id": 1,
"user": {
"id": 20710,
"username": "abc",
"first_name": "",
"last_name": "",
},
"action": {
"name": "xxx",
"date": 19/01/01,
},
},
{
"id": 2,
"user": {
"username": "xyx",
"first_name": "xxx",
"last_name": "yyy",
},
"action": {
"name": "xxx",
"date": 19/05/01,
},
},]
I want to get username of these users in a list, but i cant get the value when i get this json from api as JSONArray.
My code:
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Log.d("Create Response", response.toString());
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = response;
try {
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
JSONObject c=response.getJSONObject(1);
String id = c.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
feeds_List.add(map);
}
}
I cannot use
JSONObject object=JsonArray.getJSONObject("user");
here,
it only accept int for getJSONObject("user"); if it is JSONArray
You can use like this also.Suppose response String is userInfo
ArrayList<String> usernames = new ArrayList<String>();
JSONArray userList = new JSONArray(userInfo);
for (int j = 0; j < userList.length(); j++) {
JSONObject userObject = new JSONObject(userList.getString(j));
String user = userObject.getString("user");
JSONObject usernameInfo = new JSONObject(user);
usernames.add(usernameInfo.getString("username"));
}
Try this, if not working please mention me in comment.

Twitter search api entities with media not working with Json.net for Windows phone Mango silverlight

Below is my returned json from twitter
{
"created_at": "Sat, 11 Feb 2012 06:38:28 +0000",
"entities": {
"hashtags": [
{
"text": "Shubhdin",
"indices": [
9,
18
]
}
],
"urls": [],
"user_mentions": [
{
"screen_name": "SAMdLaw",
"name": "Sabyasachi Mohapatra",
"id": 104420398,
"id_str": "104420398",
"indices": [
0,
8
]
}
]
},
"from_user": "nilayshah80",
"from_user_id": 213599118,
"from_user_id_str": "213599118",
"from_user_name": "Nilay Shah",
"geo": {
"coordinates": [
18.6003,
73.825
],
"type": "Point"
},
"id": 168222351106899968,
"id_str": "168222351106899968",
"iso_language_code": "in",
"metadata": {
"result_type": "recent"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"source": "<a href="http://twabbit.wordpress.com/" rel="nofollow">twabbit</a>",
"text": "#SAMdLaw #Shubhdin mitra",
"to_user": "SAMdLaw",
"to_user_id": 104420398,
"to_user_id_str": "104420398",
"to_user_name": "Sabyasachi Mohapatra",
"in_reply_to_status_id": 168219865197461505,
"in_reply_to_status_id_str": "168219865197461505"
},
{
"created_at": "Sun, 12 Feb 2012 01:54:07 +0000",
"entities": {
"hashtags": [
{
"text": "IWIllAlwaysLoveYou",
"indices": [
88,
107
]
}
],
"urls": [],
"user_mentions": [],
"media": [
{
"id": 168513175187238912,
"id_str": "168513175187238912",
"indices": [
108,
128
],
"media_url": "http://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"media_url_https": "https://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"url": "http://shortener.twitter.com/dRc4dXH3",
"display_url": "pic.twitter.com/dRc4dXH3",
"expanded_url": "http://twitter.com/RIPWhitneyH/status/168513175183044608/photo/1",
"type": "photo",
"sizes": {
"orig": {
"w": 395,
"h": 594,
"resize": "fit"
},
"large": {
"w": 395,
"h": 594,
"resize": "fit"
},
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 340,
"h": 511,
"resize": "fit"
},
"medium": {
"w": 395,
"h": 594,
"resize": "fit"
}
}
}
]
},
"from_user": "RIPWhitneyH",
"from_user_id": 19319043,
"from_user_id_str": "19319043",
"from_user_name": "RIP Whitney Houston",
"geo": null,
"id": 168513175183044608,
"id_str": "168513175183044608",
"iso_language_code": "en",
"metadata": {
"recent_retweets": 8,
"result_type": "popular"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"source": "<a href="http://twitter.com/">web</a>",
"text": "R-T if you think that the Grammy's should organize an \"R.I.P. Whitney Houston\" tribute. #IWIllAlwaysLoveYou http://shortener.twitter.com/dRc4dXH3",
"to_user": null,
"to_user_id": null,
"to_user_id_str": null,
"to_user_name": null
},
If you noticed Media under entities not available in above 2 and when i tried to call below snippet gives me null reference error
MediaUrl = (from user in tweet["entities"]["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
Same code work for Entities/URL, Hashtags and mentions but not for Media.
Also tried this -> Get JSON object node but still getting null reference exception.
In first tweet, entities object doesn't have media property, so when evaluating first tweet, your code would be equivalent to :
MediaUrl = (from user in (IEnumerable<JToken>)null
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
which will throw ArgumentNullException because that code does query on null reference collection.
Finally got working. Not appropriate solution but works for me.
I created separate method for parsing Media. Passed Entity as string and in that method i checked is EntityString.Contains Media or not. If yes, then parse media json else returned null. See below Snippet.
if (Entities != string.Empty)
{
if (Entities.Contains("\"media\":"))
{
JObject searchResult = JObject.Parse(Entities);
returnMedia = (from user in searchResult["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList();
}
}
This works for me. If you have any better solution then Please let me know.

Resources