Can i change the value inside the compare method? Error - variable need to be declared final, but final wont allow me to change.
I want to compare some other variables the JSONarray(like total_transit_time, total_walking_time). i cant think of another solution to do that. could someone teach me an easier way to do it?
public JSONArray findShortest(JSONObject json_object) throws JSONException {
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < json_object.length(); i++) {
int name = i;
JSONObject json_array = json_object.optJSONObject(""+name);
jsonList.add(json_array);
}
System.out.println("jsonList = " + jsonList.toString());
Collections.sort(jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = String.valueOf(a.get("total_duration"));
valB = String.valueOf(b.get("total_duration"));
} catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
to this
public JSONArray findShortest(JSONObject json_object, String sortByThisElement) throws JSONException {
......
......
try {
valA = String.valueOf(a.get(sortByThisElement));
valB = String.valueOf(b.get(sortByThisElement));
} catch (JSONException e) {
//do something
}
......
}
});
You can declare your sortByThisElement to be final,then you can use it directly:
public JSONArray findShortest(JSONObject json_object, final String sortByThisElement) throws JSONException {
......
......
try {
valA = String.valueOf(a.get(sortByThisElement));
valB = String.valueOf(b.get(sortByThisElement));
} catch (JSONException e) {
//do something
}
......
}
});
the other way is,create a final variable in your method,then visit it in your compare method:
public JSONArray findShortest(JSONObject json_object, String sortByThisElement) throws JSONException {
......
......
System.out.println("jsonList = " + jsonList.toString());
final String sortByThis = sortByThisElement;//note this should be add before Collections.sort
........
try {
valA = String.valueOf(a.get(sortByThis));
valB = String.valueOf(b.get(sortByThis));
} catch (JSONException e) {
//do something
}
......
}
});
Related
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
System.out.println("Sentence is:: " + s);
System.out.println("Id is:: " + id);
System.out.println("text file is:: " + txtFile);
}
} catch (JSONException e) {
e.printStackTrace();
}
currently, the above code is able to print out all the records. However, I would like to change the system.out.println into return variables such as return ID, return txtFile, return sentence. How to do that?
Create an Object. use an arraylist to store your object and use it later.
public class myItem{
String sentence;
int id;
String txtfile;
public myItem(){
}
public String getSentence(){
return sentence;
}
public setSentence(String s){
this.sentence = sentence;
}
}
public void yourFunction(){
try {
ArrayList <myItem> myList = new ArrayList();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
myItem newItem = new myItem();
newItem.setSentence(s);
myList.add(newItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I agree with what Zhi Kai said in the comment.
PS. I can't comment yet so I'm writing this as an answer.
Create a POJO and u se data structure. In your case you are using a for loop so I assume you need to return a list of values from your JSONArray.
Here's what you can do.
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
Updated:
public class YourObject {
private String id;
private String txtFile;
private String sentence;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTxtFile() {
return txtFile;
}
public void setTxtFile(String txtFile) {
this.txtFile = txtFile;
}
public String getSentence() {
return sentence;
}
public void setSentence(String sentence) {
this.sentence = sentence;
}
}
public List<YourObject> returnObject(){
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
}
I'm new in JSON, but I try to use all answers and didn't work. Help please, what I doing wrong.
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
editText.setText(s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray resultArray = jsonObject.getJSONArray("query");
addresses = new ArrayList<String>();
for (int i = 0; i<resultArray.length(); i++){
addresses.add(resultArray.getJSONObject(i).getString("Name"));
Log.d("DTA",resultArray.getJSONObject(i).getString("Name"));
}
refreshAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
It's my JSON for parsing.
{
"query":{
"count":2,
"created":"2016-10-04T19:50:08Z",
"lang":"ru",
"results":{
"rate":[
{
"id":"USDRUB",
"Name":"USD/RUB",
"Rate":"62.8240",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"62.8416",
"Bid":"62.8240"
},
{
"id":"EURRUB",
"Name":"EUR/RUB",
"Rate":"70.3460",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"70.3740",
"Bid":"70.3460"
}
]
}
}
}
That's because query is not an array, it is an object. I guess you want to get the objects from rate, this is how to do it:
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject resultsObject = jsonObject.getJSONObject("results");
JSONArray resultArray = resultsObject.getJSONArray("rate");
... etc... now iterate
I am building an android application and I am new to json. I am fetching below josn formate -
{
"contact"[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}
I am using below code to fetch key1 value. Now problem I am facing is how to fetch key3 value -
jsonString = http.makeServiceCall(url, ServiceHandler.GET, null);
if (jsonString != null) {
try {
JSONObject jsonObj = new JSONObject(jsonString);
// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < questions.length(); i++) {
temp_obj = questions.getJSONObject(i);
key1Array.add(temp_obj.getString("key1").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Please help me
If you want to use Gson to parse your json data. Let try it:
First of all, you must modify your json like this:
{
"contact":[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}
Second add Gson to your libs and sync build.gradle: download here extract it, and copy/past gson-2.2.4.gson to libs folder.
Third Create some class:
FullContents.java:
public class FullContents {
private List<ObjectKey> contact;
public List<ObjectKey> getContact() {
return contact;
}
public void setContact(List<ObjectKey> contact) {
this.contact = contact;
}
}
ObjectKey.java:
public class ObjectKey {
private String key1;
private List<ObjectKey3> key2;
public List<ObjectKey3> getKey2() {
return key2;
}
public void setKey2(List<ObjectKey3> key2) {
this.key2 = key2;
}
public String getKey1(){
return key1;
}
public void setKey1(String key1){
this.key1 = key1;
}
}
ObjectKey3.java:
public class ObjectKey3 {
private String key3;
public String getKey3(){
return key3;
}
public void setKey3(String key3){
this.key3 = key3;
}
}
And Finally, get data from url:
private class ParseByGson extends AsyncTask<String,Void,FullContents> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected FullContents doInBackground(String... params) {
FullContents fullContents = null;
try {
URL url=new URL(params[0]);
InputStreamReader reader=new InputStreamReader(url.openStream(),"UTF-8");
fullContents=new Gson().fromJson(reader,FullContents.class);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fullContents;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(FullContents results) {
super.onPostExecute(results);
ObjectKey objectKey = results.getContact().get(0);
Log.e(">>",objectKey.getKey1()+"--");
}
}
you can put below code to onCreate:
ParseByGson parseByGson = new ParseByGson();
parseByGson.execute(urlStringHere);
Update: Explain
1st of all: your json appears to be not valid (missing ':' after "content");
After reviewing thins:
You can use the named getters to retrieve many types of results (object, int, string, etc);
JSONObject contact = jsonObj.getJSONObject("contact"); // {"key1":"hey1","key2":[{"key3":"hey2"}]}
or
String key1 = jsonObj.getString("key1"); // hey1
To retrieve key3, you should use:
JSONObject contact = jsonObj.getJSONObject("contact");
JSONObject key2 = contact.getJSONObject("key2");
String key3 = key2.getString("key3");
Adapt the following code to what you are coding
for (int i = 0; i < questions.length(); i++) {
temp_obj = questions.getJSONObject(i);
key1Array.add(temp_obj.getString("key1"));
JSONObject temp_objKey2 = temp_obj.getJSONObject("key2");
Key2Object key2Object = new Key2Object();
key2Object.add(temp_objKey2.getString("key3"));
key1Array.add(key2Object);
}
Overview; i need to create a json from a List to store in a sqlLite database. When i try to create the json Eclipse gets me an error that the variable List must be static. If this variable changed to static my application shows incorrect results and it's not a good thing. This is the class in which i create the json
public class Soluzione {
public String durata;
public List<Corsa> corse;
public Soluzione() {
corse = new ArrayList<Corsa>();
}
#Override
public String toString() {
StringBuilder str = new StringBuilder();
for (Corsa corsa : corse) {
if (str.length() > 0)
str.append('\n');
str.append(corsa.toString());
}
return str.toString();
}
public static JSONObject CreateJSon(List<Corsa> corse)
{
JSONObject jObj = new JSONObject();
try
{
Corsa prima = Soluzione.corse.get(0);
Corsa ultima = Soluzione.corse.get(corse.size()-1);
jObj.put("oraPartenza", prima.oraPartenza);
jObj.put("oraArrivo", ultima.oraArrivo);
jObj.put("partenza", prima.partenza);
jObj.put("arrivo", ultima.arrivo);
} catch (Exception e) { e.printStackTrace(); }
return jObj;
}
}
It is ambiguous between your field corse and the parameter of your method Create JSON.
Do not make method static and remove parameter
public JSONObject CreateJSon()
{
JSONObject jObj = new JSONObject();
try
{
Corsa prima = Soluzione.corse.get(0);
Corsa ultima = Soluzione.corse.get(corse.size()-1);
jObj.put("oraPartenza", prima.oraPartenza);
jObj.put("oraArrivo", ultima.oraArrivo);
jObj.put("partenza", prima.partenza);
jObj.put("arrivo", ultima.arrivo);
} catch (Exception e) { e.printStackTrace(); }
return jObj;
}
EDIT :
so if you want to keep CreateJSon static, rename the parameter name to avoid ambiguity then :
Soluzione soluzione = new Soluzione();
Soluzione.CreateJSon (soluzione.corse);
OR you want to remove static attribute and you can remove parameter and you do :
Soluzione soluzione = new Soluzione();
soluzione.CreateJSon ();
I am trying to learn something about JAVA and the best way to do this is creating something I would actually use and know what the purpose of it is.
I am trying to communicate with HyperV (WMI Library).
For example I found the following, my question is: how to use it? I am using Netbeans to create the GUI.
http://www.paulneve.com/wlab/javadoc/org/paulneve/wlab/virtualisation/VirtualisationAccessHyperVImpl.html
Also, how to load jInterop into my project so I can use it?
Thank you.
You can use JInterop for managing all operations of HyperV.
Download JInterop from here.
Add all JInterop jar files to your project build path.
Following is an example of getting all VMs of Hyper server:
public class ManageHyperV {
static final int RETURN_IMMEDIATE = 0x10;
static final int FORWARD_ONLY = 0x20;
private static final int STOP = 0;
private static final int START = 1;
static IJIDispatch msvmServices = null;
private static IJIDispatch createCOMServer(String namespace) { //root//virtualization
JIComServer comServer;
try {
JISystem.getLogger().setLevel(Level.WARNING);
JISystem.setAutoRegisteration(true);
JISession session = JISession.createSession(domainName,userName,password);
session.useSessionSecurity(false);
comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"),hostIP,session);
IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));
//parameters to connect to WbemScripting.SWbemLocator
Object[] params = new Object[] {
new JIString(hostIP),//strServer
new JIString(namespace),//strNamespace
// new JIString("ROOT\\CIMV2"),
JIVariant.OPTIONAL_PARAM(),//strUser
JIVariant.OPTIONAL_PARAM(),//strPassword
JIVariant.OPTIONAL_PARAM(),//strLocale
JIVariant.OPTIONAL_PARAM(),//strAuthority
new Integer(0),//iSecurityFlags
JIVariant.OPTIONAL_PARAM()//objwbemNamedValueSet
};
JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
IJIDispatch wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
return wbemServices;
} catch (JIException jie) {
System.out.println(jie.getMessage());
jie.printStackTrace();
} catch (JIRuntimeException jire) {
jire.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void getVMList() throws JIException {
String temp = "select * from Msvm_ComputerSystem";
String[] arrQuery = new String[]{temp};
for (int k=0;k<arrQuery.length;k++) {
Object[] params = new Object[] {
new JIString(arrQuery[k]),
JIVariant.OPTIONAL_PARAM(),
new JIVariant(new Integer(RETURN_IMMEDIATE + FORWARD_ONLY))
};
JIVariant[] servicesSet = msvmServices.callMethodA("ExecQuery", params);
iterateEnum(servicesSet);
}
}
private static void iterateEnum(JIVariant[] servicesSet) {
try {
IJIDispatch wbemObjectSet = (IJIDispatch) narrowObject(servicesSet[0].getObjectAsComObject());
JIVariant newEnumvariant = wbemObjectSet.get("_NewEnum");
IJIComObject enumComObject = newEnumvariant.getObjectAsComObject();
IJIEnumVariant enumVariant = (IJIEnumVariant) narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));
List<Object[]> respArr = getEnumIterations(enumVariant);
for (Object[] elements : respArr) {
JIArray aJIArray = (JIArray) elements[0];
JIVariant[] array = (JIVariant[]) aJIArray.getArrayInstance();
for (JIVariant variant : array) {
IJIDispatch wbemObjectDispatch = (IJIDispatch) narrowObject(variant.getObjectAsComObject());
JIVariant[] v = wbemObjectDispatch.callMethodA("GetObjectText_", new Object[] {});
System.out.println("----------------------------------------------------------------------");
System.out.println(v[0].getObjectAsString().getString());
System.out.println("----------------------------------------------------------------------");
}
}
} catch (JIRuntimeException e) {
e.printStackTrace();
} catch (JIException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
msvmServices = createCOMServer("root\\virtualization");
getVMList();
}
}
private static List<Object[]> getEnumIterations(IJIEnumVariant enumVariant) {
List<Object[]> list = new ArrayList<Object[]>();
int i=0;
for (i=0;i<100;i++) {
try {
list.add(enumVariant.next(1));
}catch (JIRuntimeException jre) {
break;
}
catch (JIException jie) {
break;
}
catch (Exception e) {
break;
}
}
return list;
}
Also, provide administrator username and password.
It should work.
Thanks.