Get value from JSON and put it in String - java

it's my first question here, i've try to be the more explicit :)
I want get value from a JSON page : https://api.dailymotion.com/video/x3p6d9r?fields=onair.
I have follow a tutorial about json object.
But i want get the value "onair" and put this in a String for use a IF STRING == "XX".
This is my code :
public class notification extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
detectonline();
}
public void detectonline(){
/*
if (xx == "false") {
Do something is live is off
}
else{
Do something is live is on
}
*/
}
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonText).getAsJsonObject();
return !json.get("onair").isJsonNull();
}
private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
StringBuilder sb = new StringBuilder();
Scanner scanner = null;
try{
//scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
scanner = new Scanner(page.openStream());
while (scanner.hasNextLine()){
sb.append(scanner.nextLine());
}
}finally{
if (scanner!=null)
scanner.close();
}
return sb.toString();
}
}

I remake your method according what you are looking for it's one of several way to parse json data :
public static boolean checkIfOnline(String channel) throws JSONException, IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JSONObject json = new JSONObject(jsonText); // You create a json object from your string jsonText
if(json.has("onair")) { // just a simple test to check the node that you need existe
boolean value = json.getBoolean("onair"); // In the url that you gave onair value is boolean type
return value;
}
return false;
}

I will create methode using your way !
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
String myString =json.get("onair");
return mystring;}

Related

How to Parse JSON object from a REST ENDPOINT?

I want to parse a JSON object from an endpoint (this one here: https://api.coinmarketcap.com/v1/ticker/bitcoin/) and store the value in a variable at a specific attribute, which in this case is the name.
This the ERROR i get:
java.lang.IllegalStateException: Expected a name but was STRING...
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// All your networking logic
// should be here
try {
String u = "https://api.coinmarketcap.com/v1/ticker/bitcoin";
URL coinMarketCapApi = new URL(u);
HttpsURLConnection myConnection = (HttpsURLConnection) coinMarketCapApi.openConnection();
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
if (myConnection.getResponseCode() == 200) {
// Success
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginArray();
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if (key.equals("name")) {
String value = jsonReader.nextName();
break; // Break out of the loop
} else {
jsonReader.skipValue();
}
}
jsonReader.close();
myConnection.disconnect();
} else {
// Error handling code goes here
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
you can convert the InputStream to String and then Create JSONArray from that string. like
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
JSONArray jsonarray = new JSONArray(theString);
This way you don't have to manually construct the array.
Use this depandency for JSONArray
https://mvnrepository.com/artifact/org.json/json
You can fix the problem using gson.
https://github.com/google/gson
com.google.gson.stream.JsonReader jsonReader =
new com.google.gson.stream.JsonReader(new InputStreamReader(responseBody));
ArrayList<Coin> coins = new Gson().fromJson(jsonReader, Coin.class);
coins.forEach(coin -> System.out.println(coin.name));
public class Coin{
private String id;
private String name;
private String symbol;
private int rank;
#SerializedName("price_usd")
private double priceUsd;
...........
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public int getRank() {
return rank;
}
public double getPriceUsd() {
return priceUsd;
}
..........
}

Json parsing with nested array using Gson

I have not seen an (answered) example on the web which discusses this kind of nested-json-array.
JSON to be parsed:
{
"Field": {
"ObjectsList": [
{
"type": "Num",
"priority": "Low",
"size": 3.43
},
{
"type": "Str",
"priority": "Med",
"size": 2.61
}
]
}
}
I created a class for each 'level' of nested json block. I want to be able to parse the contents of the "ObjectList" array.
Can anyone help me to parse this JSON using Gson in Java?
Any hints or code-snippets would be greatly appreciated.
My approach is the following:
public static void main (String... args) throws Exception
{
URL jsonUrl = new URL("http://jsonUrl.com") // cannot share the url
try (InputStream input = jsonUrl.openStream();
BufferedReader buffReader = new BufferedReader (new InputStreamReader (input, "UTF-8")))
{
Gson gson = new GsonBuilder().create();
ClassA classA = gson.fromJson(buffReader, ClassA.class);
System.out.println(classA);
}
}
}
class ClassA
{
private String field;
// getter & setter //
}
class ClassB
{
private List<ClassC> objList;
// getter & setter //
}
clas ClassC
{
private String type;
private String priority;
private double size;
// getters & setters //
public String printStr()
{
return String.format(type, priority, size);
}
}
The following snippet and source file would help you:
https://github.com/matpalm/common-crawl-quick-hacks/blob/master/links_in_metadata/src/com/matpalm/MetaDataToTldLinks.java#L17
private static ParseResult NO_LINKS = new ParseResult(new HashSet<String>(), 0);
private JsonParser parser;
public static void main(String[] s) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(s[0]));
MetaDataToTldLinks metaDataToTldLinks = new MetaDataToTldLinks();
while (reader.ready()) {
String[] fields = reader.readLine().split("\t");
ParseResult outboundLinks = metaDataToTldLinks.outboundLinks(fields[1]);
System.out.println(tldOf(fields[0]) + " " + outboundLinks.links);
}
}
public MetaDataToTldLinks() {
this.parser = new JsonParser();
}
public ParseResult outboundLinks(String jsonMetaData) {
JsonObject metaData = parser.parse(jsonMetaData.toString()).getAsJsonObject();
if (!"SUCCESS".equals(metaData.get("disposition").getAsString()))
return NO_LINKS;
JsonElement content = metaData.get("content");
if (content == null)
return NO_LINKS;
JsonArray links = content.getAsJsonObject().getAsJsonArray("links");
if (links == null)
return NO_LINKS;
Set<String> outboundLinks = new HashSet<String>();
int numNull = 0;
for (JsonElement linke : links) {
JsonObject link = linke.getAsJsonObject();
if ("a".equals(link.get("type").getAsString())) { // anchor
String tld = tldOf(link.get("href").getAsString());
if (tld == null)
++numNull;
else
outboundLinks.add(tld);
}
}
return new ParseResult(outboundLinks, numNull);
}
public static String tldOf(String url) {
try {
String tld = new URI(url).getHost();
if (tld==null)
return null;
if (tld.startsWith("www."))
tld = tld.substring(4);
tld = tld.trim();
return tld.length()==0 ? null : tld;
}
catch (URISyntaxException e) {
return null;
}
}
public static class ParseResult {
public final Set<String> links;
public final int numNull;
public ParseResult(Set<String> links, int numNull) {
this.links = links;
this.numNull = numNull;
}
}
How about this snippet?:
if (json.isJsonArray()) {
JsonArray array = json.getAsJsonArray();
List<Object> out = Lists.newArrayListWithCapacity(array.size());
for (JsonElement item : array) {
out.add(toRawTypes(item));
}
}

Android - How can I print the result in a TextView?

I shoul use setText() but how should I use it instead of System.out.println()?
I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question.
public class JsonReader extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
//TextView tv = (TextView) findViewById( R.id.tv );
//tv.setText(json.toString());
//tv.setText(json.get("display"));
}
}
You will need to print the result in a TextView if you want to view the result on phone instead of LogCat console as suggested by johnrao07.
To print result in a TextView first add a TextView widget in activity_main.xml layout file.
<TextView
android:id="#+id/text_view_id"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Then JsonReader.java class main function instead of System.out.println(json.toString()); call ((TextView) findViewById(R.id.text_view_id)).setText(json.toString());
You need to use Logs to print and debug stuff in android.
Generally there are five methods,
Log.v() Log.d() Log.i() Log.w() and Log.e()
v for Verbose
d for Debug
i for Info
w for Warnings
e for Error
In your case
Log.d("Key", json.toString() + "");
Log.d("Key", json.get("display") + "");
And you look for the values in the log cat, using the "Key"
You can use a CharArrayWriter to collect the output:
CharArrayWriter writer = new CharArrayWriter();
// write your stuff
TextView view = ...
view.setText(writer.toString());
You'll have to use the methods available to a Writer rather than those of a PrintStream such as System.out (no println() methods).
If you want to use basically the same calls to generate the output, you can create a ByteArrayOutputStream and wrap it in a PrintStream. After writing (and closing the PrintStream), retrieve the byte array from the ByteArrayOutputStream and convert it to a String using one of the String constructors. You just have to specify the character encoding you want to use, both when creating the PrintStream and when converting the bytes to a String.
Another alternative would be to replace printing with simply appending your data to a StringBuilder.
A final alternative is simply to append directly to the TextView, but that requires converting every piece of output to some sort of CharSequence.
public class JsonReader extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable(){
public void run(){
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
runOnUiThread(new Runnable(){
public void run(){
TextView tv = (TextView) findViewById( R.id.tv );
tv.setText(json.toString());
tv.setText(json.get("display"));
}
});
}
}).start();
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
//move to onCreate
}
}

How to get all post id's of a specific page in facebook

I am extracting the post details of a facebook page. I extracted the json of a particular page and now I have to get id of all the posts of that page. How can I do it using facebook4j.
private static String readpage(Reader rd) throws IOException
{
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1)
{
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readurl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try
{
BufferedReader rd = new BufferedReader(new InputStreamReader
(is, Charset.forName("UTF-8")));
String jsonText = readpage(rd);
JSONObject json = new JSONObject(jsonText);
return json;
}
finally
{
is.close();
}
}
public static void main(String[] args) throws
IOException, JSONException, FacebookException
{
JSONObject json = readurl("https://graph.facebook.com/"+s);
}
You can obtain all the post related information of a particular page by referring the following code :
ResponseList<Post> results = facebook.getPosts(searchPost);
String userId = "";
for (Post post : results) {
obj.put("Post Id", post.getId());
obj.put("Post message", post.getMessage());
obj.put("No of likes on Post", post.getLikes().size());
obj.put("Post owner name:", post.getFrom().getName());
objArray = new JSONArray();
where obj is a JSON object.
PS:I am using eclipse kepler and facebook4j-core-2.0.2

Test Design: How to test a method properly without rewriting it completely?

I have the following class which contains a hard coded URL that never changes:
public class HttpClient {
private final String DOWNLOAD_URL = "http://original.url.json";
public String readJsonDataFromUrl() throws IOException {
URLConnection urlConnection = getUrlConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer content = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
content.append(readLine);
}
return content.toString();
}
private URLConnection getUrlConnection() throws IOException {
URL jsonLocator = new URL(DOWNLOAD_URL);
return jsonLocator.openConnection();
}
}
Now imagine that I'd like to expect the IOException in my test. In my opinion, the only way to do that is to rewrite the complete class in a mock object because of the final variable:
public class HttpClientMock extends HttpClient {
private final String DOWNLOAD_URL = "http://wrong.test.url.json";
#Override
public String readJsonDataFromUrl() throws IOException {
URLConnection urlConnection = getUrlConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer content = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
content.append(readLine);
}
return content.toString();
}
private URLConnection getUrlConnection() throws IOException {
URL jsonLocator = new URL(DOWNLOAD_URL);
URLConnection urlConnection = jsonLocator.openConnection();
return urlConnection;
}
}
But this is somehow far-fetched. If the original methods would be changed, the test results could still be positive because with this attempt, I don't actually test the original class anymore.
How can this be done properly? (I don't want to use a framework just for this one test, so are there any design attempts to solve this in a common way?)
Another spin on Gilbert Le Blanc's suggestion, is to make the HttpClient totally ignorant of the URL by injecting it through the constructor.
public class HttpClient {
private final String url;
public HttpClient(String url) { this.url = url; }
}
You can hard code the URL (or read from a config) somewhere externally to HttpClient and inject it wherever you instantiate the client. Then in your test it will be trivial to inject a bad url.
Thanks to everybody, but I think that Gilbert Le Blanc's solution is the most preferable for that case which looks like this:
The original class:
public class HttpClient {
private final String DOWNLOAD_URL = "http://my.original.json.url";
public String readJsonDataFromUrl() throws IOException {
URLConnection urlConnection = getUrlConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuffer content = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
content.append(readLine);
}
return content.toString();
}
private URLConnection getUrlConnection() throws IOException {
URL jsonLocator = new URL(getConnectionString());
return jsonLocator.openConnection();
}
protected String getConnectionString() {
return DOWNLOAD_URL;
}
}
The mock object:
public class HttpClientMock extends HttpClient {
private String downloadUrl = "http://my.original.json.url";
public HttpClientMock() {
super();
}
public HttpClientMock(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
#Override
protected String getConnectionString() {
return downloadUrl;
}
}
And the working tests:
public class HttpClientTest {
private JSONParser jsonParser = new JSONParser();
#Test
public void readJsonDataFromUrlSucceeds() throws IOException, ParseException {
HttpClient httpClient = new HttpClientMock();
String jsonString = httpClient.readJsonDataFromUrl();
JSONObject jsonObject = (JSONObject)jsonParser.parse(jsonString);
assertTrue(jsonObject.size() > 0);
}
#Test(expected = IOException.class)
public void readJsonDataFromMalformedUrlFails() throws IOException, ParseException {
HttpClient httpClient = new HttpClientMock("http://malformed");
httpClient.readJsonDataFromUrl();
}
}

Categories