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!)
Related
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);
Hello im trying to use a post request to pull in strings and integers in the body of the request ,what is the best way to do this ?
entering something like this in a rest client for example :
{
"name":"ExName",
"reading":"100"
}
#POST
#Path("/SetFeeds")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#JsonCreator
//public String setFeed(#PathParam("name")String name2, #QueryParam("name") String name,#Context UriInfo uriInfo,String jsonBody){
public String setFeed(String jsonBody,#Context UriInfo uriInfo){
MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
String query = uriInfo.getRequestUri().getQuery();
String response = queryParams.getFirst("name");
System.out.println(response);
//System.out.println(name2);
//JSONObject jsonObject = new JSONObject();
//JSONObject nodeStats = name.get(getJSONObject("name"));
// Getting the value of a attribute in a JSONObject
//String sSDR = actualObj.getString("sdr");
//FeedObjects x=new FeedObjects();
//System.out.println(x.getName());
return response;
}
You might want to consider creating a class that you want and use gson library to convert object to json.
I think it will be much more easier with less "dirty work".
Check it here:
https://github.com/google/gson
Here's an example from: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
DataObject obj = new DataObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
try {
//write converted json data to a file named "file.json"
FileWriter writer = new FileWriter("c:\\file.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(json);
}
}
Hi guys I have problem in Java. The problem is around parsing JSON with Jackson as I was instructed. My JSON is parsed well, that's not the problem. The problem lies in that I have multiple JSON items in one JSON. I've parsed it like this:
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Unit> unitList = objectMapper.readValue(json,List.class);
System.out.println("UnitSize " + String.valueOf(unitList.size()));
System.out.println(unitList.get(0).getUnitEmail());
} catch (IOException e) {
e.printStackTrace();
}
and at UnitSize it'll tell me that I have precisely 5 objects of Unit type, which is okay, but when I want to get something out of the List it says me this:
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.reddatura.API.HTTPRequest$Unit
I've googled it, but nothing relevant. What should be the problem
EDIT:
here is my class snippet:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Unit
{
#JsonProperty("unitid")
int unitId;
#JsonProperty("unitname")
String unitName;
#JsonProperty("unitlogo")
String unitLogo;
#JsonProperty("unitaddress")
String unitAddr;
//other fields, getters setters
#JsonCreator
public Unit()
{
}
}
I want to parse into this model
I think you are not casting correctly your json value:
Using jackson you could do the following:
List<Unit> myUnits = objectMapper.readValue(json, objectMapper.getTypeFactory().
constructCollectionType(List.class, Unit.class));
Hope it helps :)
try this
ObjectMapper objectMapper = new ObjectMapper();
try {
Unit[] unit = objectMapper.readValue(jsonString, Unit[].class);
Log.i("TEST", String.valueOf(unit.length)+" ******* "+unit[1].getUnitEmail()+" ******* "+unit[1].getUnitName());
// or
List<Unit> unit1 = objectMapper.readValue(jsonString, new TypeReference<List<Unit>>() { });
Log.i("TEST_1", String.valueOf(unit1.size())+" ****11111*** "+unit1.get(1).getUnitEmail()+" **1111111**** "+unit1.get(1).getUnitName());
} catch (IOException e) {
e.printStackTrace();
}
do something like this :
JSONObject jObject = new JSONObject(jsonString);
JSONArray jsonArray = jObject.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
int a = jsonArray.getJSONObject(i).getInt("a"),
String s = jsonArray.getJSONObject(i).getString("b"));
}
jsonString is String variable and must be Json syntax
Hi i'm trying to parse json array from this url. The json array looks like this.
[
{
"id":1,
"introtext":"\u041b\u0438\u043c\u0443\u0437\u0438\u043d\u0430\u0442\u0430 \u0435 \u043e\u0434 \u0430\u043c\u0435\u0440\u0438\u043a\u0430\u043d\u0441\u043a\u043e \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0441\u0442\u0432\u043e \u0432\u043e \u0431\u0435\u043b\u0430 \u0431\u043e\u0458\u0430 \u0434\u043e\u043b\u0433\u0430 \u043e\u043a\u043e\u043b\u0443 8,5 \u043c\u0435\u0442\u0440\u0438. \u041e\u043f\u0440\u0435\u043c\u0435\u043d\u0430 \u0435 \u0441\u043e \u043a\u043b\u0438\u043c\u0430 \u0440\u0435\u0434, \u0422\u0412, \u0414\u0412\u0414 \u0438 \u0431\u0430\u0440. \u041c\u043e\u0436\u0430\u0442 \u0434\u0430 \u0441\u0435 \u0432\u043e\u0437\u0430\u0442 \u0434\u043e 9 \u043b\u0438\u0446\u0430. \u0421\u0435 \u0438\u0437\u043d\u0430\u0458\u043c\u0443\u0432\u0430 \u0441\u043e \u043d\u0430\u0448 \u0448\u043e\u0444\u0435\u0440.\n{AdmirorGallery}..\/katalog\/prevoz\/limo-servis-jasmina\/linkoln\/{\/AdmirorGallery}\n\u00a0",
"image":"http:\/\/zasvadba.mk\/media\/k2\/items\/cache\/787ae9ec9023a82f5aa7e4c1a64f73cb_S.jpg",
"title":"\u041b\u0438\u043c\u0443\u0437\u0438\u043d\u0430 \u041b\u0438\u043d\u043a\u043e\u043b\u043d",
"catid":"20",
"alias":"\u043b\u0438\u043c\u0443\u0437\u0438\u043d\u0430-\u043b\u0438\u043d\u043a\u043e\u043b\u043d-\u043b\u0438\u043c\u043e-\u0441\u0435\u0440\u0432\u0438\u0441-\u0458\u0430\u0441\u043c\u0438\u043d\u0430"
}
]
I'm doing this in my java class
try {
JSONfunctions j=new JSONfunctions();
JSONObject json = j.getJSONfromURL(url);
Log.i("log_tag", json.toString());
String jsonvalues = json.getString("id");
Log.i("DARE", jsonvalues);
}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
}
}
But it doesn't work, can anybody help me parse my json array
you will need to make two changes in your current code according to string u have posted here for parsing as Json :
First : change the return type of getJSONfromURL method to JSONArray and return JSONArray from it instead of JSONObject
For example :
public JSONArray getJSONfromURL(String url){
String str_response="response from server";
// convert response to JSONArray
JSONArray json_Array=new JSONArray(str_response);
return json_Array; //<< retun jsonArray
}
Second : change your code as for getting value from JsonArray :
try {
JSONfunctions j=new JSONfunctions();
JSONArray jArray = j.getJSONfromURL(url);
Log.i("log_tag", jArray.toString());
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String jsonvalues = json_data.getString("id");
// .. get all value here
Log.i("DARE", jsonvalues);
}
}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
}
Of course it doesn't work! You should use json.getJSONArray(...) method for parsing arrays in Json :)
You can Easily do it using gson library.
Here is the code sample:
Your Entity Class will like:
public class ResponseEntity {
#SerializedName("id")
public int id;
#SerializedName("introtext")
public String introtext;
#SerializedName("image")
public String image;
#SerializedName("title")
public String title;
#SerializedName("catid")
public String catid;
#SerializedName("alias")
public String alias;
}
Now Convert this json Array using GSON library.
Gson gson=new Gson();
ResponseEntity[] entities = gson.fromJson(yourResponseAsString.toString(),
ResponseEntity[].class);
Now you have the entity array at entities.
Thanks.
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;