Json object returning null against given key - java

I'm trying to read JSON from string (obtained from web), but it returns null.
Specifically, result.append(name + id); gives me nullnull
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(datJ);
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
Integer id = (Integer) jsonObject.get("id");
result.append(name + id);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (org.json.simple.parser.ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Consider that datJ contains following JSON string:
{
"rikeard":{
"id":2828822,
"name":"Rikeard",
"profileIconId":688,
"summonerLevel":30,
"revisionDate":1422917445000
}
}
EDIT: Final code working
JSONParser parser = new JSONParser();
try {
String datJ = IOUtils.toString(new URL(url));
Object obj = parser.parse(datJ);
JSONObject rikeardObject = (JSONObject) ((Map<?, ?>) obj).get("rikeard");
String name = (String) rikeardObject.get("name");
Long id = (Long) rikeardObject.get("id");
Special Thanks for Sufian and Ved!

"id" and "name" are inside the JSON object against the key "rikeard". So you need to make changes like following:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(datJ);
JSONObject jsonObject = (JSONObject) obj;
JSONObject rikeardObject = (JSONObject) obj.get("rikeard");
String name = (String) rikeardObject.get("name");
Integer id = (Integer) rikeardObject.get("id");
result.append(name + id);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (org.json.simple.parser.ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Use this method it's work for me,
private void extractJson(){
String jsonString="{\"rikeard\":{\"id\":2828822,\"name\":\"Rikeard\",\"profileIconId\":688,\"summonerLevel\":30,\"revisionDate\":1422917445000}}";
try {
JSONObject jsonObject=new JSONObject(jsonString);
if(jsonObject!=null){
jsonObject=jsonObject.optJSONObject("rikeard");
if(jsonObject!=null){
String id=jsonObject.optString("id");
Log.d("MainActivity","id="+id);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Try this:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(datJ);
JSONObject jsonObject = (JSONObject) obj;
JSONObject rikeardObject = (JSONObject) jsonObject.get("rikeard");;
String name = (String) rikeardObject .get("name");
Integer id = (Integer) rikeardObject .get("id");
result.append(name + id);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (org.json.simple.parser.ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Related

Java SocketException: Network is unreachable, but the URL works in the browser

I am trying to read some data via a GET request as
URL corpusDbUrl = null;
try {
corpusDbUrl = new URL("http://xxx.cc.ww.tt:1234/erwet/erherh/iouiiu");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URLConnection corpusDbConn = null;
try {
corpusDbConn = corpusDbUrl.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(corpusDbConn.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String inputLine="";
try {
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
} catch (Exception e) { // TODO Auto-generated catch block
e.printStackTrace();
}
and i get
java.net.SocketException: Network is unreachable
but when i try the URL in browser, it works just fine. What am i doing wrong?

InvocationTargetException for ClassLoaders.callStaticFunction Java Eclipse

I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}

jLabel output won't output text within same instance of GUI

I have a jLabel that is supposed to output the computer name based on an active directory search. The computer name gets assigned to the variable "CN" no problem, but it won't show up on the jLabel unless I run the gui again. How can I get the jLabel text to appear in real time within the same instance of the gui? The CN variable appears towards the bottom of the code posted.
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
// textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(
ldapName.size() - 1).getValue();
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
}
});
try (BufferedReader br = new BufferedReader(new FileReader("resultofbatch.txt")))
{
final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
try {
while ((sCurrentLine = br.readLine()) != null) {
String[] tokens = PATTERN.split(","); //This will return you a array, containing the string array splitted by what you write inside it.
//should be in your case the split, since they are seperated by ","
// System.out.println(sCurrentLine);
CN = sCurrentLine.split("CN=",-1)[1].split(",",-1)[0];
System.out.println(CN);
testLabel.setText(CN);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
New code added
#Override
protected Integer doInBackground() throws Exception {
System.out.println(CN);
testLabel.setText(CN);
return null;
}

JSON-SIMPLE Can't cast to object to read through array

I'm trying to use JSON-Simple to read a configuration file that's in JSON using the following code
File f = new File("config.json");
JSONParser parser = new JSONParser();
try {
int i;
StringBuilder out = new StringBuilder();
FileReader reader = new FileReader(f);
while ((i = reader.read()) != -1) {
out.append((char) i);
}
JSONArray array = (JSONArray) JSONValue.parse(out.toString());
} catch (Exception e) {
System.out.println(e.toString());
}
or
File f = new File("config.json");
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(f));
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("module");
Iterator<String> itreator = array.iterator();
while (itreator.hasNext()) {
System.out.println(itreator.next());
}
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but both are returning the error
org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
however when doing
File f = new File("config.json");
try {
System.out.println(JSONValue.parse(new FileReader(f)));
} catch (Exception e) {
System.out.println(e.toString());
}
it returns the file's contents.
The config file can be seen here:
http://pastebin.com/5xJTHSwj
module tag in your config file isn't array. JSON array starts with [
e.g.
"module" : [{prop : "One"},{prop : "Two"}]
Use this code instead
JSONObject moduleObject= (JSONObject ) jsonObject.get("module");

Android really long execution time of HTTP request

i have a problem in my app. At start i will describe how it works. It send request to the server (which wasn't created by me), and in the response i am getting JSON string ( it's not so big average 10 records in JSONarray) there in one parameter there is URL to the picture which i download and save as a bitmap for every JSON object. To summarize i download a JSON which looks like:
{
"id":"125",
"description":"desc",
"type":"type",
"state":"state",
"date":"2012-09-22 10:40:46.0",
"lat":"52.321911",
"lng":"19.464111",
"author":"user",
"photo":"GetImage?size=small&id=0",
"comments":[
]
}
x 10 for example, and then i download from URL "photo" image for every object. Problem lies in the time of execution, it is really really long which it should't it is not big data. Here it is how i do this: AsyncClass that download image:
private class HttpGetImage extends AsyncTask<Object, Integer, Integer>
{
public boolean ready = false;
public boolean success = false;
#Override
protected Integer doInBackground(Object... obj) {
DefaultHttpClient client = new MyHttpClient(ViewEdit.this);
HttpGet get = new HttpGet(url+photoUrl);
HttpResponse getResponse = null;
try {
getResponse = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
HttpEntity responseEntity = getResponse.getEntity();
BufferedHttpEntity httpEntity = null;
try {
httpEntity = new BufferedHttpEntity(responseEntity);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
ready=true; return null;
}
InputStream imageStream = null;
try {
imageStream = httpEntity.getContent();
m_orders.get((Integer)obj[1])
.setOrderBitmap(BitmapFactory.decodeStream(imageStream));
success = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} finally {
try {
imageStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
}
ready = true;
return null;
}
}
and AsyncClass for jsonString:
private class HttpGetNotifications extends AsyncTask<Double, Integer, Integer>
{
public boolean ready = false;
public boolean success = false;
#Override
protected Integer doInBackground(Double... params)
{
DefaultHttpClient client = new MyHttpClient(ViewEdit.this);
HttpGet get = new HttpGet(url + Double.toString(params[0]) + "&longitude=" + Double.toString(params[1]) + "&radius="+distance);
HttpResponse getResponse = null;
try {
getResponse = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
HttpEntity responseEntity = getResponse.getEntity();
String entityContents="";
try {
entityContents = EntityUtils.toString(responseEntity);
loadNotifications(entityContents);
success = true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ready=true; return null;
}
ready = true;
return null;
}
public void loadNotifications(String jsonstring) throws JSONException
{
JSONObject jsonResponse = new JSONObject(jsonstring);
JSONArray notifi = jsonResponse.getJSONArray("notifications");
for (int i =0, count = notifi.length(); i <count; i++){
//storage of data
}
}
}
Maybe you guys have an idea how can i optimize that code to reduce a time of execution?
Put in some profiling to find what's taking the time. In each of your AsyncTasks:
private long time0, time1;
#Override protected void onPreExecute() {
time0 = System.currentTimeMillis();
}
#Override protected void onPostExecute(HttpResponse response) {
time1 = System.currentTimeMillis();
long deltaT = (time1 - time0);
Log.d(TAG, "Execute took "+deltaT+"ms");
}
And then go from there.

Categories

Resources