How to Parse JSON String in LWUIT - json

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.

Related

pretty print Json with Spring boot, only works with console

I have this code,
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(strJson); //works fine here
return strJson; //return it doesn't display pretty on browser
Any idea how to fix this? I've been trying all the solution here on the internet and especially stackoverflow and none of it works.
If you want clear view, it's from my previous code
I use thymeleaf html again,
#Controller
#RequestMapping("/menu")
public class DataController {
// load json
private List<DataModel> theDatawiz;
private String strJson = null;
#PostConstruct
private void loadData() {
// load json
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
// setup array mapper
ObjectMapper objectMapper = new ObjectMapper();
DataModel[] datawiz = null;
try {
datawiz = objectMapper.readValue(strJson, DataModel[].class);
} catch (Exception e) {
e.printStackTrace();
}
// create the list
theDatawiz = new ArrayList<>();
for(int i = 0; i < datawiz.length; i++) {
DataModel dat = new DataModel(datawiz[i].getId(),datawiz[i].getName());
theDatawiz.add(dat);
}
}
// add mapping for "/list"
#GetMapping("/list")
public String listMenu(Model theModel) {
// add to the spring model
theModel.addAttribute("thelist", theDatawiz);
return "menu-list";
}
// add mapping for "/list"
#GetMapping("/jason")
public String printJson(Model theModel) {
// add to the spring model
theModel.addAttribute("result", strJson);
return "jason";
}
}
On the jason.html,
<p th:text="'JSON: ' + ${result}" style="white-space: pre"></p>

parsing Json in Android Studio when result is empty

I try to load datas from a Json that is on my server to my smartphone.
When the json is like this, it works and i get the label "spanishguitar":
{"file": "image.jpg", "objects": [{"bbox": [611, 82, 1231, 1265], "label": "spanishguitar", "prob": 0.991}]}
Here is my code:
public void updateLabel() {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
if (200 == jsonResponse.getStatusLine().getStatusCode()) {
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonResult jsonResult = new Gson().fromJson(json, JsonResult.class);
instrumentname = jsonResult.objects.get(0).label;
But sometimes the json is empty like this:
{"file": "image.jpg", "objects": []}
So my plan is that if objects == null to get something like:
Toast.makeText(getApplicationContext(), "Uuuups, itÅ› empty", Toast.LENGTH_SHORT).show();
Do you know how to parse the json, so that i get a message in the case of an empty "objects"?
Thank you!
Now it works. Here is my code:
#RequiresApi(api = Build.VERSION_CODES.N)
private void empty() throws IOException {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(String.valueOf(json));
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if (objects == null || objects.size() == 0) {
/////////////
runOnUiThread(new Runnable() {
#Override
public void run() {
noResult.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Identification failed", Toast.LENGTH_SHORT).show();
}});
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.INVISIBLE);
} else {
updateLabel();
}
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
Thank you a lot for your help!
'Empty' is not 'null'.You can use
ArrayUtils.isEmpty(objects)
or
objects == null || objects.length() == 0
to detect whether you got an empty objects.
I writed a demo for you:
import com.google.gson.*;
public class Main
{
public static void main(String[] args)
{
JsonParser parser = new JsonParser();
// JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": []}");
JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": [{\"bbox\": [611, 82, 1231, 1265], \"label\": \"spanishguitar\", \"prob\": 0.991}]}");
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if(objects == null || objects.size() == 0) {
System.out.println("objects is empty");
}else{
JsonObject firstObj = objects.get(0).getAsJsonObject();
System.out.println("objects[0].label="+firstObj.get("label"));
}
}
}

Received Data Provider Mismatch error

Tried below code but receiving Data Provider Mismatch error. Could anyone help out on this?
package appModules;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
public class NewTest {
public WebDriver driver;
public WebDriverWait wait;
String appURL =
"https://dev.agencyport.rsagroup.ca:8443/agencyportal/ProcessLogoff";
//Locators
private By username = By.id("USERID");
private By password = By.id("PASSWORD");
#BeforeClass
public void testSetup() {
System.setProperty("webdriver.firefox.marionette",
"C:\\Automation\\geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);
}
#Test(dataProvider = "login")
public void Login(String Username, String Password) {
driver.findElement(username).sendKeys(Username);
driver.findElement(password).sendKeys(Password);
}
#DataProvider (name="login")
public Object[][] dp() throws Exception{
Object[][] arrayObject =
getExcelData("C:\\Automation\\testData.xls","New");
return arrayObject;
}
public String[][] getExcelData(String fileName, String sheetName) throws
Exception {
String[][] arrayExcelData = null;
try {
FileInputStream fs = new FileInputStream(fileName);
Workbook wb = Workbook.getWorkbook(fs);
Sheet sh = wb.getSheet(sheetName);
int totalNoOfCols = sh.getColumns();
System.out.println(totalNoOfCols);
int totalNoOfRows = sh.getRows();
System.out.println(totalNoOfRows);
arrayExcelData = new String[totalNoOfRows-1][totalNoOfCols];
for (int i=1 ; i <totalNoOfRows; i++) {
for (int j=0; j <totalNoOfCols; j++) {
arrayExcelData[i-1][j] = sh.getCell(j, i).getContents();
System.out.println(arrayExcelData[i-1][j]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayExcelData;
}
#Test
public void tearDown() {
driver.quit();
}
}
Received below error -
org.testng.internal.reflect.MethodMatcherException:
Data provider mismatch
Method: Login([Parameter{index=0, type=java.lang.String,
declaredAnnotations=[]}, Parameter{index=1, type=java.lang.String,
declaredAnnotations=[]}])
Arguments: [(java.lang.String) agent,(java.lang.String) password,
(java.lang.String) ]
atorg.testng.internal.reflect.DataProviderMethodMatcher.getConformingArguments(DataProviderMethodMatcher.java:45)
at org.testng.internal.Parameters.injectParameters(Parameters.java:796)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:982)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)`
You are passing return value of arrayObject with incorrect Data Type,
You need to get String value from Excel File in Data Provider Method, and That you need to pass in Object.
Refer below Example, for Reference:
#DataProvider
public Iterator<Object[]> getTestData()
{
ArrayList<Object[]> testdata = new ArrayList<Object[]>();
try {
reader = new excelUtility(excelTestDataFile);
} catch (Exception e) {
e.printStackTrace();
}
sheetName = className;
for (int rowNumber = 2; rowNumber <= reader.getRowCount(sheetName); rowNumber++) {
String caseNo = reader.getCellData(sheetName, "Case", rowNumber);
String emailid = reader.getCellData(sheetName, "Email ID", rowNumber);
String password = reader.getCellData(sheetName, "Password", rowNumber);
String message = reader.getCellData(sheetName, "Expected Result", rowNumber);
Object ob[] =
{ caseNo, emailid, password, message };
testdata.add(ob);
}
return testdata.iterator();
}
And this is the #Test Receiver of Data Provider:
#Test(dataProvider = "getTestData")
public void calllogin(String caseNO, String emailid, String password, String expectedResult) throws Exception
{
******
}

Json parsing Using Volley does not get cahced

I Parse json using volley framework, which every time gets response from the server, does not check the cache, It has taken a whole day, Here is my code. Any of you have used volley for parsing json are expected to help
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(diag_url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
// handle data, like converting it to xml, json, bitmap etc.,
// Parsing json
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
try {
DiagRegPojo test = new DiagRegPojo();
JSONObject obj = jsonArray.getJSONObject(i);
String testName = obj.getString("content");
Log.d("Response From Cache", testName);
test.setTitle(testName);
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
// Creating volley request obj
JsonArrayRequest testReq = new JsonArrayRequest(diag_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
DiagRegPojo test = new DiagRegPojo();
test.setTitle(obj.getString("content"));
Log.d("Response From Server", obj.getString("content"));
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
})
{
//**
// Passing some request headers
//*
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Set-Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Content-Type", "application/x-www-form-urlencoded");
//headers.put("Content-Type","application/json");
headers.put("Accept", "application/x-www-form-urlencoded");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(testReq);
}
}
To cache images, I have used this. sure it can be of some help to you.
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
.
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}

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