So I already succeed with one Json to get it all worked. Now I have another class where I want to get only one attribute. I have now a moviedatabase class (which work with JSON and gets all the information) and now I want to add a Trailer which is from Youtube API. so basically I need it to be added into the same JSON to make it easier for me in the future to get it into a HTML. the only problem is I cant get it work. I get a syntax error JSON when using this method.
EDIT CODE 1.1:
Youtube attribute:
public class FilmAttribut {
private String title = "";
private String release = "";
private int vote = 0;
private String overview = "";
private String poster = "";
private String trailer = "";
// getters + setters stripped
}
Youtube class:
public class Youtube {
FilmAttribut movie = new FilmAttribut();
public void search(String trailer, FilmAttribut in) {
HttpResponse<JsonNode> response;
try {
response = Unirest.get("https://www.googleapis.com/youtube/v3/search?key=[app key here]&part=snippet")
.queryString("q", trailer + " trailer")
.asJson();
JsonNode json = response.getBody();
JSONObject envelope = json.getObject();
JSONArray items = envelope.getJSONArray("items");
in.setTrailer("https://youtu.be/" + items.getJSONObject(0).getJSONObject("id").getString("videoId")); //Gives me error here
}
catch (JSONException e) {
e.printStackTrace();
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
}
and main method
public class WebService {
public static void main(String[] args) {
setPort(1337);
Gson gson = new Gson();
Youtube yt = new Youtube();
MovieDataBase mdb = new MovieDataBase();
get("/search/:movie", (req, res) -> {
String titel = req.params(":movie");
FilmAttribut film = mdb.searchMovie(titel);
yt.search(titel, film);
String json = gson.toJson(film);
return json;
});
So I think the problem is that you can't have two gson.toJson(film) + gson.toJson(trailer); Because it makes the JSON twice, where one time is for the film (aka. movie) and then a new json is created with trailer which make the syntax error.
So my real question is, is it possible to have another class like I have now youtube. to send the information to a attribute class where I have all my attributes and then run it in main-method so that I can get all the JSON in one JSON.
If I did understand well what you are asking, yes you can, but I would do something like that instead:
public void search(String trailer, FileAttribut in) {
// fetch the trailer from youtube (NB: you should use getters/setters, not public fields)
in.setTrailer("https://youtu.be/" + items.getJSONObject(0).getJSONObject("id").getString("videoId"));
}
and:
FilmAttribut film = mdb.searchMovie(titel);
yt.search(titel, film); // pass "film" to "fill" its trailer
return gson.toJson(film);
OR
public String search(String trailer) {
// fetch the trailer from youtube
return "https://youtu.be/" + items.getJSONObject(0).getJSONObject("id").getString("videoId");
}
and:
FilmAttribut film = mdb.searchMovie(titel);
film.setTrailer(yt.search(titel));
return gson.toJson(film);
Related
I've got a problem with data driven testing in cucumber. I want to get data from json file. I've prepared scenario:
Feature: data provider
Scenario Outline: Data driven using json file
Given account user
And Get System Variables
And Delete TB report if already exist
When user navigates to TB report
Then Select Filters On Reports Page from <data>
Example:
|data|
|test|
Data json object:
[
{
"fundName": "test",
"currentDate": "31/12/2020"
},
"fundName": "test2",
"currentDate": "31/12/2020"
}
Pojo class for storing data:
public class Data {
public String fundName;
public String currentDate;
}
Data json reader:
private final String path = "path/to/file";
private List<Data> data;
public JsonDataReader(){
DataList = getData();
}
private List<Data> getData() {
Gson gson = new Gson();
BufferedReader bufferReader = null;
try {
bufferReader = new BufferedReader(new FileReader(path));
Data[] data= gson.fromJson(bufferReader, Data[].class);
return Arrays.asList(data);
}catch(FileNotFoundException e) {
throw new RuntimeException("Json file not found at path : " + path);
}finally {
try { if(bufferReader != null) bufferReader.close();}
catch (IOException ignore) {}
}
}
public final Data getDataByName(String name){
return dataList.stream().filter(x -> x.fundName.equalsIgnoreCase(name)).findAny().get();
}
Step definition:
#Then("Select Filters On Reports Page from \\\"(.*)\\\"$")
public void selectMultipleFilters(String name) {
Data data = FileReaderManager.getInstance().getJsonDataReader().getFundByName(name);
reportSteps.selectMultipleFiltersForReports(data);
}
But when I try to run this I've got an error on 5th step:
java.util.NoSuchElementException: No value present
at JsonDataReader.getDataByName
Can someone tell me what am I doing wrong?
I have some problem fetching info from JSON. I'm confused about whether to use ArrayList or any other data type to retrieve data from JSON server.
I've tried to fetch data using
ArrayList<String>
in model.
Below is data format of JSON
[
{
"sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
"mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"
},
{
"sun_timing": "{\"sun_from\":\"12:30\",\"sun_to\":\"4:30\"}",
"mon_timing": "{\"mon_from\":\"3:00\",\"mon_to\":\"4:30\"}"
}
]
I want to fetch all sun_timing data and mon_timing data.
That is sun_from,sun_to and mon_from,mon_to data.
Your Plain Old Java Object(POJO) for your json looks like this:
public class Example {
#SerializedName("sun_timing")
#Expose
private String sunTiming;
#SerializedName("mon_timing")
#Expose
private String monTiming;
public String getSunTiming() {
return sunTiming;
}
public void setSunTiming(String sunTiming) {
this.sunTiming = sunTiming;
}
public String getMonTiming() {
return monTiming;
}
public void setMonTiming(String monTiming) {
this.monTiming = monTiming;
}
}
See also: https://stackoverflow.com/a/40973753/10452701 for more details about How to get json via Rerofit2.
try this out working for me
private List<String> getSunList() {
ArrayList sunList = new ArrayList<String>()
String sun_json = your_json_string
try {
JSONObject jsonObject = new JSONObject(sun_json)
Log.d(TAG, "jsonObject: "+jsonObject)
Log.d(TAG, "jsonObject: "+sun_json)
JSONArray jsonArray = jsonObject.getJSONArray("sun_timing")
for (i in 0 until jsonArray.length())
{
JSONObject obj = jsonArray.get(i) as JSONObject
String sun_from = obj.getString("sun_from")
String sun_to = obj.getString("sun_to")
sunList.add(sun_from)
Log.d(TAG, "obj= "+obj)
}
}
catch (e: java.lang.Exception)
{
}
return sunList
}
My plan is to make a JSON results by my database. What I mean is that I have made a Class where I connect to a API (etc. TMDB) and take the information I need.
public class MovieDataBase {
Attributes att = new Attributes(); //A klass where I have setter-getter
//methods for titel, overview, vote, release.
public String searchMovie(String filmtitel) {
HttpResponse<JsonNode> response;
try {
response = Unirest.get("http://api.themoviedb.org/3/search/movie")
.queryString("api_key", "123")
.queryString("query", filmtitel)
.asJson();
JsonNode json = response.getBody();
JSONObject envelope = json.getObject();
JSONArray results = envelope.getJSONArray("results");
filmtitel += att.title = results.getJSONObject(0).getString("title");
filmtitel += att.release = results.getJSONObject(0).getString("release_date");
filmtitel += att.vote = results.getJSONObject(0).getInt("vote_average");
filmtitel += att.overview = results.getJSONObject(0).getString("overview");
return filmtitel
}
catch (JSONException e) {
and I also have a get method where I want to create a JSON construction of the program to easier use it in the future (for html)
public static void main(String[] args) {
Gson gson = new Gson();
setPort(8080);
Youtube yt = new Youtube();
MovieDataBase mdb = new MovieDataBase();
get("/search/:movie", (req, res) -> {
String movie = req.queryParams(":movie");
String movies = mdb.searchMovie(movie);
String json = att.title + att.release + att.vote + att.vote + att.overview
json = gson.toJson(json);
return json
});
This did not work. I'm getting a null when I'm running it, not a error but only a null. So I have to combine String movies = mdb.searchMovie(movie); with the String Json and then make it look like a json, but I don't know if that's right.
Suppose I am fetching from an api some json array as so
[{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]
I want to retrieve this json as an Some object from URL_Some url
public class Some implements Serializable {
private String id;
private String title;
private String description;
private String vote;
private String created_at;
private String updated_at;
}//with all getters and setters
.
public List<Some> getSome() throws IOException {
try {
HttpRequest request = execute(HttpRequest.get(URL_Some));
SomeWrapper response = fromJson(request, SomeWrapper.class);
Field[] fields = response.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
try {
Log.i("TAG", (String) fields[i].get(response));
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Log.i("TAG", fields[i].getName());
}
if (response != null && response.results != null)
return response.results;
return Collections.emptyList();
} catch (HttpRequestException e) {
throw e.getCause();
}
}
and SomeWrapper is simply
private static class SomeWrapper {
private List<Some> results;
}
The problem is that I keep on getting this message
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY
PS : I use
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
Your json should actually be like this:
{"results": [{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]}
Gson will try to parse the json and create a SomeWrapper object. This alone tells Gson he will wait for a json with this format {...} since he's expecting an object. However you passed an array instead, that's why it complains about expecting BEGIN_OBJECT ({) but getting BEGIN_ARRAY instead ([). After that, it will expect this json object to have a results field, which will hold an array of objects.
You can create List<Some> directly without the need of a wrapper class however. To do so do this instead:
Type type= new TypeToken<List<Some>>() {}.getType();
List<Some> someList = new GsonBuilder().create().fromJson(jsonArray, type);
In this case, you can use the original json array you posted.
The JSON you posted is a JSON array, which is indicated by the squared brackets around it: [ ].
You'd have to read the first object from the JSON array.
I personally use the org.json packages for Android JSON and parse my JSON in a manner like this:
private void parseJSON(String jsonString) {
JSONArray json;
try {
json = new JSONArray(jsonString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String id = jsonObject.getString("id");
} catch (JSONException jsonex) {
jsonex.printStackTrace();
}
}
If you've got multiple JSON objects in your array you can iterate over them by using a simple for loop (not for each!)
i'm trying to retrieve text from wikipedia to use on an Android app. I'm using Java.
The first thing I want to do is to retrieve the sections from an specific article, show them to the user and, when the user clicks on one section, get the section text with another http request.
So, the two requests are these:
http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Valencia_Cathedral&prop=sections
and then this one:
http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Valencia_Cathedral&prop=text§ion=1
My question is: What kind of java objects should I create to store the information and then convert it to these classes using .fromJSON()?
Thanks to #NathanZ, I created these two classes:
public class WikiResponseSections {
String title;
List<Section> sections;
}
public class Section {
int toclevel;
String level;
String line;
String number;
String index;
String fromtitle;
int byteoffset;
String anchor;
}
But, when I convert the HTTP response to these objets by Gson, and try to read the value of the field 'title' there's an error that triggers: JavaNullPointerException.
Here's my code for the conversion:
InputStream stream = null;
try {
stream = entity.getContent();
} catch (IllegalStateException e) {
Log.e("Stream","ERROR illegalstateexception");
} catch (IOException e) {
Log.e("Stream","ERROR exception");
}
reader = new BufferedReader(new InputStreamReader(stream));
GsonBuilder bldr = new GsonBuilder();
Gson gson = bldr.create();
WikiResponse = gson.fromJson(reader, WikiResponseSections.class);
if (WikiResponse != null){
Log.i("WikiResponse",WikiResponse.getTitle()); //The error triggers HERE
publishProgress();
}
else
Log.i("WikiResponse","NULL");
}
Thanks for your help again
You can use the Google's Gson library.
It works like this:
InputStream source = ...; // your code to get the Json from a url
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
MyResponse response = gson.fromJson(reader, MyResponse.class);
Where MyResponse is your object. When you create MyResponse, give your fields the same name and type as the Json's fields
MyResponse class can be as follows:
public class MyResponse{
String title;
ArrayList<sections>;
}
public class sections{
int toclevel;
String level;
String line;
String number;
String fromtitle;
long byteoffset;
String anchor;
}
public class WikiResponseParse{
Parse parse;
public class Parse{
String title, text;
}
}
If you can't use the json fields name because it's not Java compliant:
Add the following import:
import com.google.gson.annotations.SerializedName;
and in your class:
#SerializedName("*")
public String star;