Blackberry json parser - json

I want to create a simple json parser for BlackBerry to test. I found this example, and implement my code as follows
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import org.json.me.JSONArray;
import org.json.me.JSONObject;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;
public final class MyScreen extends MainScreen
{
HttpConnection conn = null;
InputStream in = null;
String _response = null;
Vector _adBeanVector=null;
int code;
public MyScreen()
{
setTitle("MyTitle");
try
{
StringBuffer url=new StringBuffer().append("http://codeincloud.tk/json_android_example.php");
conn = (HttpConnection) Connector.open(url.toString(), Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while (-1 != (len = in.read(buffer))) {
out.write(buffer);
}
out.flush();
_response = new String(out.toByteArray());
JSONObject resObject=new JSONObject(_response);
String _key =resObject.getString("Insert Json Key");
_adBeanVector = new Vector();
JSONArray newsArray = resObject.getJSONArray("Insert Json Array Key");
if(newsArray.length() > 0)
{
for (int i=0 ;i < newsArray.length() ; i++)
{
Vector _adElementsVector=new Vector();
JSONObject newsObj = newsArray.getJSONObject(i);
_adElementsVector.addElement(newsObj.getString("message"));
//_adElementsVector.addElement(newsObj.getString("Insert Json Array Element Key2"));
_adBeanVector.addElement(_adElementsVector);
}
}
if (out != null){
out.close();
}
if (in != null){
in.close();
}
if (conn != null){
conn.close();
}
}
} catch (Exception e)
{
Dialog.alert(e.getMessage());
}
}
}
but I cannot modify it for my purpose. Can any one help me to modify this code sample to access this json. I'm very much new to this subject area.
Thank you in advance.

try this -
JSONObject resObject=new JSONObject(_response);
String _name=resObject.getString("name"); //This will get the result as Froyo
String _version=resObject.getString("version"); //This will get the result as Android 2.2
Dialo.alert("Name : "+_name+" and Version : "+_version);

Related

JSON Array conversion to CSV

I want to convert JSON to CSV. I am using the list function to meet the purpose.
But I am not getting desirable output for JSON array. Please find the sample JSON and list function which I am using:
Sample JSON document:
{
"NAME": "Viv",
"EMAIL": "lo",
"PUBLIC_OFFICIALS_CONTACTED": [{
"NAME_PUBLIC_OFFICIAL": [ "ff"],
"TITLE_PUBLIC_OFFICIAL": ["ff"]
}]
,
"COMMUNICATION_TYPE": ["Meeting","Phone","Handout","Conference"],
"NAMES_OF_OTHERS_FROM_XXX": [{
"NAME_OF_OTHERS": ["ff"],
"TITLE_OF_OTHERS": [ "ff"]
}]
,
"COMMUNICATION_BENEFIT": "Yes",
"AFFILIATE_NAME": "name",
"COMMUNICATION_ARRANGED": "Yes, arranged by you"
}
and list function which I am using is:
function(head, req) {
var row,
first = true;
// output HTTP headers
start({
headers: {
'Content-Type': 'text/csv'
}
,
});
// iterate through the result set
while(row = getRow()) {
// get the doc (include_docs=true)
var doc = row.doc;
// if this is the first row
if (first) {
// output column headers
send(Object.keys(doc).join(',') + 'n');
first = false;
}
// build up a line of output
var line = '';
// iterate through each row
for(var i in doc) {
// comma separator
if (line.length > 0) {
line += ',';
}
// output the value, ensuring values that themselves
// contain commas are enclosed in double quotes
var val = doc[i];
if (typeof val == 'string' && val.indexOf(',') > -1) {
line += '"' + val.replace(/"/g,'""') + '"';
}
else {
line += val;
}
}
line += 'n';
// send the line
send(line);
}
};
Please find attached the CSV output and expected output exported in excel.
Also, there is an issue in saving checkbox values. Please help me in writing the list function for the above JSON conversion to CSV.
current output:
expected output:
CSV is a single, flat list of values in each row, and one row of headers. The expected output shared in this question isn't compatible with CSV - it will be necessary to "flatten" your JSON by unpacking the nested data structures and making them instead into a flat hierarchy of data that can then become CSV. Try searching for "JSON to CSV" with a search engine for some examples - hope that helps!
I have refered this gitHUb link and tried the following:
JsonFlattener.class : Which will read the json string & extract the key & value
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonFlattener {
public Map<String, String> parse(JSONObject jsonObject) throws JSONException {
Map<String, String> flatJson = new HashMap<String, String>();
flatten(jsonObject, flatJson, "");
return flatJson;
}
public List<Map<String, String>> parse(JSONArray jsonArray) throws JSONException {
List<Map<String, String>> flatJson = new ArrayList<Map<String, String>>();
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, String> stringMap = parse(jsonObject);
flatJson.add(stringMap);
}
return flatJson;
}
public List<Map<String, String>> parseJson(String json) throws Exception {
List<Map<String, String>> flatJson = null;
try {
JSONObject jsonObject = new JSONObject(json);
flatJson = new ArrayList<Map<String, String>>();
flatJson.add(parse(jsonObject));
} catch (JSONException je) {
flatJson = handleAsArray(json);
}
return flatJson;
}
private List<Map<String, String>> handleAsArray(String json) throws Exception {
List<Map<String, String>> flatJson = null;
try {
JSONArray jsonArray = new JSONArray(json);
flatJson = parse(jsonArray);
} catch (Exception e) {
throw new Exception("Json might be malformed");
}
return flatJson;
}
private void flatten(JSONArray obj, Map<String, String> flatJson, String prefix) throws JSONException {
int length = obj.length();
for (int i = 0; i < length; i++) {
if (obj.get(i).getClass() == JSONArray.class) {
JSONArray jsonArray = (JSONArray) obj.get(i);
if (jsonArray.length() < 1) continue;
flatten(jsonArray, flatJson, prefix + i);
} else if (obj.get(i).getClass() == JSONObject.class) {
JSONObject jsonObject = (JSONObject) obj.get(i);
flatten(jsonObject, flatJson, prefix + (i + 1));
} else {
String value = obj.getString(i);
if (value != null)
flatJson.put(prefix + (i + 1), value);
}
}
}
private void flatten(JSONObject obj, Map<String, String> flatJson, String prefix) throws JSONException {
Iterator iterator = obj.keys();
while (iterator.hasNext()) {
String key = iterator.next().toString();
if (obj.get(key).getClass() == JSONObject.class) {
JSONObject jsonObject = (JSONObject) obj.get(key);
flatten(jsonObject, flatJson, prefix);
} else if (obj.get(key).getClass() == JSONArray.class) {
JSONArray jsonArray = (JSONArray) obj.get(key);
if (jsonArray.length() < 1) continue;
flatten(jsonArray, flatJson, key);
} else {
String value = obj.getString(key);
if (value != null && !value.equals("null"))
flatJson.put(prefix + key, value);
}
}
}
}
CSVWriter.class:Which transform the json string to CSV file
import org.apache.commons.lang.StringUtils;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class CSVWriter {
public void writeAsCSV(List<Map<String, String>> flatJson, String fileName) throws FileNotFoundException {
Set<String> headers = collectHeaders(flatJson);
String output = StringUtils.join(headers.toArray(), ",") + "\n";
for (Map<String, String> map : flatJson) {
output = output + getCommaSeperatedRow(headers, map) + "\n";
}
writeToFile(output, fileName);
}
private void writeToFile(String output, String fileName) throws FileNotFoundException {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(fileName));
writer.write(output);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(writer);
}
}
private void close(BufferedWriter writer) {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCommaSeperatedRow(Set<String> headers, Map<String, String> map) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replace(",", "");
items.add(value);
}
return StringUtils.join(items.toArray(), ",");
}
private Set<String> collectHeaders(List<Map<String, String>> flatJson) {
Set<String> headers = new TreeSet<String>();
for (Map<String, String> map : flatJson) {
headers.addAll(map.keySet());
}
return headers;
}
}
JSONtoCSV.class : which will use the above class to parse the json & write the key values as a .csv file
import java.util.List;
import java.util.Map;
public class JSONtoCSV {
public static void main(String[] args) throws Exception {
String jsonString = "{\n" +
"\"NAME\": \"Viv\",\n" +
"\"EMAIL\": \"lo\",\n" +
"\n" +
"\"PUBLIC_OFFICIALS_CONTACTED\": [{\"NAME_PUBLIC_OFFICIAL\": [ \"ff\"],\n" +
"\"TITLE_PUBLIC_OFFICIAL\": [\"ff\"]}],\n" +
"\n" +
"\"COMMUNICATION_TYPE\": [\"Meeting\",\"Phone\",\"Handout\",\"Conference\"],\n" +
"\n" +
"\"NAMES_OF_OTHERS_FROM_XXX\": [{\"NAME_OF_OTHERS\": [\"ff\"],\n" +
"\"TITLE_OF_OTHERS\": [ \"ff\"]}],\n" +
"\n" +
"\"COMMUNICATION_BENEFIT\": \"Yes\",\n" +
"\"AFFILIATE_NAME\": \"name\",\n" +
"\"COMMUNICATION_ARRANGED\": \"Yes, arranged by you\"\n" +
"}";
JsonFlattener parser = new JsonFlattener();
CSVWriter writer = new CSVWriter();
List<Map<String, String>> flatJson = parser.parseJson(jsonString);
writer.writeAsCSV(flatJson, "C:/sample.csv");
}
}

Can't parse JSON data from URL with only username authentication

I'm using an url in order to read json data but it doesn't work because there is an authentication requested to get access to it using only the username (no login, no password only username). so my code show me the error :
java.io.IOException: Server returned HTTP response code: 401 for URL
My code is working using another URL with no authentication.
Could someone help me or give me and example that do the same thing.
many thanks to you in advance
package javaapplication3;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
public class JSONREST {
public static String callURL(String myURL) {
System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null) {
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
public static void main(String[] args) {
String jsonString = callURL("MY URL");
System.out.println("\n\njsonString: " + jsonString);
try {
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}

Using XPages to get data from managed bean

I am trying to create a list of Twitter users, populating it with the number of followers for the user and their profile image. Because of Twitter's API, you need to get an access token for your application prior to using their REST API. I thought the best way to do this was via Java and a managed bean. I posted the code below, which currently works. I get the access token from Twitter, then make the API call to get the user info, which is in JSON.
My question is, what is the best way to parse the JSON and iterate over a list of user names to create a table/grid on the XPage?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class TwitterUser implements Serializable {
private static final String consumerKey = "xxxx";
private static final String consumerSecret = "xxxx";
private static final String twitterApiUrl = "https://api.twitter.com";
private static final long serialVersionUID = -2084825539627902622L;
private static String accessToken;
private String twitUser;
public TwitterUser() {
this.twitUser = null;
}
public String getTwitterUser(String screenName) {
try {
this.requestTwitterUserInfo(screenName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return twitUser;
}
public void setTwitterUser() {
twitUser = twitUser;
}
//Encodes the consumer key and secret to create the basic authorization key
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
return new String();
}
}
//Constructs the request for requesting a bearer token and returns that token as a string
private static void requestAccessToken() throws IOException {
HttpsURLConnection connection = null;
String endPointUrl = twitterApiUrl + "/oauth2/token";
String encodedCredentials = encodeKeys(consumerKey,consumerSecret);
String key = "";
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
writeRequest(connection, "grant_type=client_credentials");
// Parse the JSON response into a JSON mapped object to fetch fields from.
JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection));
if (obj != null) {
String tokenType = (String)obj.get("token_type");
String token = (String)obj.get("access_token");
accessToken = ((tokenType.equals("bearer")) && (token != null)) ? token : "";
}
else {
accessToken = null;
}
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
private void requestTwitterUserInfo(String sn) throws IOException {
HttpsURLConnection connection = null;
if (accessToken == null) {
requestAccessToken();
}
String count = "";
try {
URL url = new URL(twitterApiUrl + "/1.1/users/show.json?screen_name=" + sn);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setUseCaches(false);
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
twitUser = readResponse(connection);
}
//Writes a request to a connection
private static boolean writeRequest(HttpsURLConnection connection, String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
}
catch (IOException e) { return false; }
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpsURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
}
catch (IOException e) { return new String(); }
}
}
A few pointers:
Domino has the Apache HTTP client classes. They tend to be more robust than raw HTTP connections
Define a new class as a bean that contains all values that you want to see per row. You only need the getters public
add a method to your managed bean Collection getAllData()
bind that to a repeat control
you then can use repeatvar.someProperty in column values in EL
use better names than I just used

Google docs api for Java (exception)

I have a problem with google docs. I want to retrieve all your files by using OAuth 2.0. The problem is that once you do, and authorization when trying to download a file gives me this error:
Exception in thread "main" java.lang.NullPointerException
at GoogleBlack.readUrl(GoogleBlack.java:95)
at GoogleBlack.getDocument(GoogleBlack.java:87)
at GoogleBlack.go(GoogleBlack.java:187)
at GoogleBlack.main(GoogleBlack.java:222)
Here's the code I use
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ServiceException;
public class GoogleBlack {
private static final String APPLICATION_NAME = "Homework";
public DocsService service;
public GoogleService spreadsheetsService;
static String CLIENT_ID = "***********";
static String CLIENT_SECRET = "**************";
static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
static List<String> SCOPES = Arrays.asList("https://docs.google.com/feeds");
public void getSpreadSheet(String id, String i, String ids, String type) throws Exception {
UserToken docsToken = (UserToken) service.getAuthTokenFactory()
.getAuthToken();
UserToken spreadsheetsToken = (UserToken) spreadsheetsService
.getAuthTokenFactory().getAuthToken();
service.setUserToken(spreadsheetsToken.getValue());
URL url = null;
if(type.equals("doc"))
{
url = new URL("https://docs.google.com/feeds/download/documents/Export?id="+ ids);
}
else
{
url = new URL("https://docs.google.com/feeds/download/spreadsheets/Export?key="+ ids +"&exportFormat="+ type + "&gid=0");
i += ".xls";
}
System.out.println("Spred = " + url.toString());
readUrl1(url.toString(), i, type);
service.setUserToken(docsToken.getValue());
}
public void readUrl1(String url, String i, String type) throws IOException, ServiceException
{
MediaContent mc = new MediaContent();
mc.setUri(url);
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
}
public void getDocument(String id, String i) throws Exception {
URL url = new URL(id);
readUrl(url,i);
}
public void readUrl(URL url, String i) throws Exception {
MediaContent mc = new MediaContent();
mc.setUri(url.toString());
System.out.println("Url "+ url.toString());
System.out.println("MC: " + mc.toString());
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
// FileOutputStream fout = null;
// fout = new FileOutputStream(i);
// fout.write(cbuf.);
// fout.close();
}
static Credential getCredentials() {
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
// Step 1: Authorize -->
String authorizationUrl =
new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Read the authorization code from the standard input stream.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String code = null;
try {
code = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 1 <--
// Step 2: Exchange -->
GoogleTokenResponse response = null;
try {
response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
code, REDIRECT_URI).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 2 <--
// Build a new GoogleCredential instance and return it.
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(transport).build()
.setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
}
public void go() throws Exception {
DocsService service = new DocsService(APPLICATION_NAME);
service.setOAuth2Credentials(getCredentials());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentListFeed feed = service.getFeed(feedUrl, DocumentListFeed.class);
System.out.println("Feed " + feed.getEntries().size());
for(int i = 0; i < feed.getEntries().size(); i++)
{
DocumentListEntry entry = feed.getEntries().get(i);
if(entry.getType().equals("file"))
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
System.out.println("URL "+ UrlForDownload);
getDocument(UrlForDownload, entry.getFilename());
}
else
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("URL "+ UrlForDownload);
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
if(entry.getTitle().getPlainText().equals("Web Design 2011/2012 - Материали"))
{
continue;
}
if(entry.getType().equals("spreadsheet"))
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"xls");
}
else
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"doc");
}
}
}
}
public static void main(String[] args) throws Exception {
new GoogleBlack().go();
}
}
95 row - MediaSource ms = service.getMedia(mc);
87 row - readUrl(url,i);
187 row - getDocument(UrlForDownload, entry.getFilename());
222 row - new GoogleBlack().go();
I apologize if I am not well explained!!!
You never initialized the "public DocsService service;" member of your GoogleBlack class, so when you call "service.getMedia(mc);" you're getting a NullPointerException.

How to Parse JSON String in LWUIT

How to parse a JSON object in LWUIT,give me some example or some link from where i can read this.Suppose i have the objects given below.
"{'guild': 'Crimson', 'region': 'us', 'realm': 'Caelestrasz', 'timestamp': 1311860040}"
Json Example Code:This Code will work for json.
package com.ndtv.parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import com.ndtv.callback.jsonActivelistener;
import com.ndtv.datatype.StockActiveItem;
import json.me.JSONArray;
import json.me.JSONException;
import json.me.JSONObject;
public class StockActiveParser {
public Vector jsonObjVector = new Vector();
public JSONArray arrayObj = null;
public String name,LastPrice;
protected jsonActivelistener mjsonListener;
public static boolean ParserCanceled = false;
public void setjsonListener(jsonActivelistener listener) {
mjsonListener = listener;
}
// Non-blocking.
public void parser(final String url) {
Thread t = new Thread() {
public void run() {
// set up the network connection
try {
jsonParse(url);
}
catch (Exception e) {
mjsonListener.parserExceptionListing(e);
}
mjsonListener.parseDidFinishListing();
}
};
t.start();
}
protected void jsonParse(String url) {
StringBuffer stringBuffer = new StringBuffer();
InputStream is = null;
HttpConnection hc = null;
System.out.println(url);
try {
hc = (HttpConnection)Connector.open(url);
is = hc.openInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
}
catch (SecurityException se) {
System.out.println("security exception:"+se);
}
catch (NullPointerException npe) {
System.out.println("null pointer excception:"+npe);
}
catch (IOException ioe) {
System.out.println("io exception:"+ioe);
}
try{
hc.close();
is.close();
}catch(Exception e) {
System.out.println("Error in MostActivePareser Connection close:"+e);
e.printStackTrace();
}
String jsonData = stringBuffer.toString();
try {
JSONObject js = new JSONObject(jsonData);
JSONArray js2 = js.getJSONArray("values");
System.out.println(js2.length());
for (int i = 0; i < js2.length(); i++) {
StockActiveItem item = new StockActiveItem();
JSONObject jsObj = js2.getJSONObject(i);
item.name = jsObj.getString("name");
item.last_traded_price = jsObj.getString("last_traded_price");
item.change = jsObj.getString("change");
item.price_diff = jsObj.getString("price_diff");
item.chart=jsObj.getString("chart");
item.company_id=jsObj.getString("company_id");
mjsonListener.itemParsedListing(item);
}
} catch (JSONException e1) {
System.out.println("Json Data error:"+e1);
e1.printStackTrace();
}
catch (NullPointerException e) {
System.out.println("null error:"+e);
}
}
}
public class StockActiveItem
{
public String name ="";
public String last_traded_price ="";
public String change="";
public String price_diff ="";
public String chart="";
public String company_id="";
public String year_high="";
public String year_low="";
}
you just replace name, for example guild replacing name.If any doubt ask me.
Use LWUIT JSONParser and parser the JSON format string. Just use MIDP_IO.jar from latest LWUIT 1.5 for this.
I was able to use sample code provided in below given links successfully in my app.
http://jimmod.com/blog/2010/03/java-me-j2me-json-implementation-tutorialsample/
http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/
BTW, Latest JSON ME library can be found here : https://github.com/upictec/org.json.me/
You can use JSON jar and and import that in your project. After that create a JSON object and you can use optString or getString methods of that object accordingly to get the values.