I am going to use Twitter for some semantic text analysis in a school class. I downloaded the Hosebird Client for Java and is running the FilterStreamExample.java: https://github.com/twitter/hbc/blob/master/hbc-example/src/main/java/com/twitter/hbc/example/FilterStreamExample.java
Running it, I get a lot of data about the users' profiles, their settings, background images, etc. I just want the tweeted text only. And maybe the location and username.
It may be a stupid question, but how do I make it only display the "texts" information? Right now, it just prints out everything.
// Do whatever needs to be done with messages
for (int msgRead = 0; msgRead < 1000; msgRead++) {
String msg = queue.take();
System.out.println(msg);
}
I could probably do a search for "text" in the strings themselves, but it seems a bit cumbersome. Isn't there any better way to do it?
The response from the twitter Streaming API is JSON String. Parse the string into JSON Object and get the value from the key "text"
import org.json.*;
for (int msgRead = 0; msgRead < 1000; msgRead++) {
String msg = queue.take();
JSONObject obj = new JSONObject(msg);
String text= obj.getString("text");
System.out.println(msg);
}
*Not Tested
Refer the following for parsing JSON in Java
How to parse JSON in Java
Related
I am trying to pull Json string from url and put it into String[] inside my android application.
String i am getting from my url is "[\"What is your name?\",\"How do you do?\"]"
I am trying to create Quizz class in my app where i want to call constructor and then it pull data from url and put it into private variables.
I have tried many things but getting multiple errors (with network and other stuff) and now i am somewhere with async tasks where i got lost and think i am going totally wrong way.
Class i want to have is like this:
public class Quizz {
private String[] Questions;
public Quizz() {
// Here i want to load data from url into variable Questions
}
public String getQuestion(int id) {
return "Not implemented!";
}
}
And when i create Quizz object in my main activity i want to have questions loaded.
you can use the following article to help you decode your json
Article Link
Also, You can use JSONArray in the Following Article
Use Retrofit to Connect to API, and Use its converter to deserialize the JSON Response.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
it's very effective and has error handling built into it.
I know you are looking for a string[] array but in this case its best to use a arraylist as sizes can change when retrieving the response.
//create empty strings arraylist
List<String> strings = new Arraylist<>()
//try parse the response as a JSONarray object
try{
//get url string response as a json array
JSONArray jsonArray = (JSONArray) urlStringResponse;
//parse through json array and add to list
for(int i = 0; i < jsonArray.length(); i++){
String str = (String) jsonArray.getJSONObject(i);
strings.add(str);
}
} catch (JSONException e) {
Log.e("JSON", "Problem parsing the JSON results", e);
}
What about to use String.split() method?
val string = "[\"What is your name?\",\"How do you do?\"]"
val split: List<String> = string.subSequence(1, string.length - 1).split(',')
val array = split.toTypedArray()
array.forEach { println(it) }
And result will be
"What is your name?"
"How do you do?"
please tell me I am new to use JSON data. Thanks in Advance.
https://api.myjson.com/bins/waw4y
how to parse this data in android. I am adding the two client details. In that
First, I have added an object for the whole content and after I have added the different client names and age, car with arrays. so please make it as easy.
Thanks in advance
JSON stands for JavaScript Object Notation. It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.
Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.
The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting
temperature only.
This code is not feasible with dynamic implementation of JSON, Just to showcase the Parsing proccess.
JSONObject client = null;
try {
client = new JSONObject(response);
JSONArray clientChild1 = client.getJSONArray("client1");
JSONArray clientChild2 = client.getJSONArray("client2");
for (int j = 0; j < clientChild1.length(); j++) {
JSONObject objectChild = clientChild1.getJSONObject(j);
Log.e("NAME", "onCreate: " + objectChild.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
I have a big excel file and I want to show the data on my website. I have made a matlab and a Java program(script) that can extract the information I want from the excel file. How do I get the data to the website?
Should I have the matlab or java script running on a server and then make a javascript that in some way connects to the server? How would i do this?
Or should a make a javascript that directly reads the excel file?
I am a beginner in web development so I dont really know where to start...
I happened to do something like this while I had to analyze the grades I gave. What I did was export the Excel sheet as a CSV, and then put that in a website where I used JavaScript to first convert it to a JSON. This is the function I used to perform the conversion:
function csvJSON(csv){
var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}
And then it was simple. to use. Let's say I put in a textarea the exported CSV, for instance:
Name,Grade1,Grade2
Bobby,87,12
Rakesh,9,3
//...
Then I called csvJSON() with this data to get:
[{"Name":"Bobby","Grade1":87,"Grade2":12},{"Name":"Rakesh","Grade1":9,"Grade2":3},/*...*/]
Which is especially easy to use. For instance:
var csv = ""; // get it from somewhere
var json = JSON.parse(csvJSON(csv));
for (int i = 0; i < json.length; i++)
{
var obj = json[i];
var name = obj.Name, Grade1 = obj.Grade1, Grade2 = obj.Grade2;
//Do something
}
(Prefacing this by saying that I am extremely new to JSON, aside from the last several hours I have spent trying to figure this out)
I am working on a personal android app that will search a URL that includes JSON data.
For example:
http://magictcgprices.appspot.com/api/images/imageurl.json?cardname=Pillar%20of%20Flame&cardset=fnmp
Provides the link to the card picture url.
Basically, it is a tool for Magic the Gathering so that I can search a card name and either have the picture shown to me, or bring the prices up with this URL:
http://magictcgprices.appspot.com/api/tcgplayer/price.json?cardname=Tarmogoyf&cardset=Modern%20Masters ----> Returns: ["$97.25", "$115.20", "$149.98"]
However, these JSON arrays do not have field names. I am stuck on how I will go about retrieving the JSON results from the webpage and relaying them back to java so I can manipulate them again. I have messed around with Jackson JSON libraries with no luck.
Try this..
JSONArray new_array = new JSONArray(response);
for(int i = 0; i < new_array.length; i++){
System.out.println("Values : "+new_array.getString(i));
}
This should help:
JSONArray yourData = new JSONArray(response);
int len = yourData.length();
String data;
for (int i = 0; i < len; i++) {
data = new String(yourData.get(i));
System.out.println(data);
}
I've written Socket Communication server with Java and a AIR programm with AS3, using Socket connection.
The communication through socket connection is done with JSON serialization.
Sometimes with really long JSON strungs over socket, AS3 code says that there is a JSON parse error.
Each JSON string I end with end string to let programm know, that it is not the end of the message, so this is not the problem with AIR programm reading the message in parts.
The error occurs only with realy long json string, for example, string with 78031 length. Is there any limits for JSON serialization?
I had the same problem. The problem is in Flash app reading data from socket.
The point is that Flash ProgressEvent.SOCKET_DATA event fires even when server didn't send all the data, and something is left (especially when the data is big and the connection is slow).
So something like {"key":"value"} comes in two (or more) parts, like: {"key":"val and ue"}. Also sometimes you might receive several joined JSONs in one message like {"json1key":"value"}{"json2key":"value"} - built-in Flash JSON parser cannot handle these too.
To fight this I recommend you to modify your SocketData handler in the Flash app to add a cache for received strings. Like this:
// declaring vars
private var _socket:Socket;
private var _cache: String = "";
// adding EventListener
_socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
private function onSocketData(e: Event):void
{
// take the incoming data from socket
var fromServer: ByteArray = new ByteArray;
while (_socket.bytesAvailable)
{
_socket.readBytes(fromServer);
}
var receivedToString: String = fromServer.toString();
_cache += receivedToString;
if (receivedToString.length == 0) return; // nothing to parse
// convert that long string to the Vector of JSONs
// here is very small and not fail-safe alghoritm of detecting separate JSONs in one long String
var jsonPart: String = "";
var jsonVector: Vector.<String> = new Vector.<String>;
var bracketsCount: int = 0;
var endOfLastJson: int = 0;
for (var i: int = 0; i < _cache.length; i++)
{
if (_cache.charAt(i) == "{") bracketsCount += 1;
if (bracketsCount > 0) jsonPart = jsonPart.concat(_cache.charAt(i));
if (_cache.charAt(i) == "}")
{
bracketsCount -= 1;
if (bracketsCount == 0)
{
jsonVector.push(jsonPart);
jsonPart = "";
endOfLastJson = i;
}
}
}
// removing part that isn't needed anymore
if (jsonVector.length > 0)
{
_cache = _cache.substr(endOfLastJson + 1);
}
for each (var part: String in jsonVector)
{
trace("RECEIVED: " + part); // voila! here is the full received JSON
}
}
According to Adobe, it appears that you are not facing a JSON problem but instead a Socket limitation.
A String you may send over a Socket via writeUTF and readUTF is limited by 65,535 bytes. This is due to the string being prepended with a 16 bit unsigned integer rather than a null terminated string.