My Json Response is
"results": [
[
"2C30AE32-191#Local",
"Imperva Inc.",
"SecureSphere",
"Custom Violation",
1,
"",
"KMB",
"196.207.98.94",
"10.10.1.180",
"10.10.18.14",
443,
"",
7874115,
"",
1522716763000,
"TCP",
"",
"",
""
]
]
My java Code :
String output = response.getEntity(String.class);
JSONObject obj = new JSONObject(output);
JSONArray results = obj.getJSONArray("results");
JSONArray first = (JSONArray) results.get(1);
String deviceVendor = (String) first.get(0);
String deviceProduct = (String) first.get(1);
String name = (String) first.get(2);
String baseEventCount = (String) first.get(3);
String categoryOutcome = (String) first.get(4);
String customerName = (String) first.get(5);
String sourceAddress = (String) first.get(6);
String destinationAddress = (String) first.get(7);
String deviceAddress = (String) first.get(8);
String destinationPort = (String) first.get(9);
String destinationServiceName = (String) first.get(10);
String eventId = (String) first.get(11);
String message = (String) first.get(12);
String startTime = (String) first.get(13);
String transportProtocol = (String) first.get(14);
String categoryBehavior = (String) first.get(15);
String categoryDeviceGroup = (String) first.get(16);
String categoryObject = (String) first.get(17);
Here, I am taking index number to get the data. when I am parsing it I am getting JSONArray[5] not found exception. How to handle this. if we have a json object we can handle using .has("string") but if it is json array how to handle this situation ?
I have use simplejson you can replace the net.sf.JSON
it's working.
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\Users\\user\\Desktop\\results.json"));
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) obj;
org.json.simple.JSONArray departures = (org.json.simple.JSONArray) jsonObject.get("results");
for(int i=0;i<departures.size();i++){
System.out.println("all =="+departures.get(0));
org.json.simple.JSONArray all = (org.json.simple.JSONArray) departures.get(0);
System.out.println("test =="+all.get(5));
}
Related
String sessionCookie = req.getReader().lines().reduce("",String::concat);
JSONObject jsonObject = HTTP.toJSONObject(sessionCookie);
String someString = jsonObject.getString("sessionId");
The value of sessionCookie is {"sessionId":"foo"}, however the line String someString = jsonObject.getString("sessionId"); gives this error:
org.json.JSONException: JSONObject["sessionId"] not found.
What am I doing wrong here?
This is what I should have done:
String sessionCookie = req.getReader().lines().reduce("",String::concat);
JSONObject jsonObject = new JSONObject(sessionCookie);
String sessionId = jsonObject.getString("sessionId");
public static void smth()
throws ParseException, FileNotFoundException, IOException, InterruptedException {
JSONParser parser = new JSONParser();
FileReader reader = new FileReader("release.json");
Object obj = parser.parse(reader); // Parse JSON data of file
JSONObject json = (JSONObject) obj;
String version = (String) json.get("version");
String license = (String) json.get("license");
String licenseFile = (String) json.get("LICENSE.txt?");
String date = (String) json.get("date");
String author = (String) json.get("author");
String contrib = (String) json.get("contributors");
String lib = (String) json.get("libraries");
String[] values = { version, license, author, contrib, date, lib, licenseFile };
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
}
JSON.simple returns null, why? My JSON does have a keys corresponding to the json.get("key");.
I followed a tutorial and my tree is similar to the tutorial's code. I have printed one of them just to debug, when printing the array values, it just prints out null for every json.get("key"); statment
My JSON:
{
"release": {
"version": "0.0.1 InDev",
"license": "GNU General Public License v3",
"LICENSE.txt?" : "Webber/LICENSE.txt",
"date" : "18th Februaru, 2022 # 4:59PM Indian Standard Time",
"author" : "Habis Muhammed",
"contributors" : "***** 🙁 Nobody *****",
"libraries":"json-simple"
}
}
JSONObject json = (JSONObject) obj;
json = (JSONObject) json.get("release");
String version = (String) json.get("version");
You can try this.
You have to traverse from JSON object root
JSON file:
[
{
"name":"John",
"city":"Berlin",
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"job":"Doctor"
}
]
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader("F:\file.json"));
for (Object o : a) {
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
if (name.equalsIgnoreCase("john")) {
String name1 = (String) person.get("name");
System.out.println("name1" + name1);
String city1 = (String) person.get("city");
System.out.println("city1" + city1);
String job1 = (String) person.get("job");
System.out.println("job1" + job1);
person.put("city", "BLR");
String city2 = (String) person.get("city");
System.out.println("city2" + city2);
}
}
Value are not updating in Json external file
JSONObject is a represent of json that does not link to originally file.
To rewrite file you need to change values in person and write it to file.
person.put("city", "BLR");
String jsonString = person.toString();
// write jsonString to file
This is the response I tried to parse and try to get the value in the separate strings,
response =
"Data1{
key1='4722**********6',
key2='2107',
key3=value{
value1='226',
value2=passed,
value3=tracked,
value4=noted
},
isChecked=true
}"
but unable to parse the response, like
String Datas = "Data1{key1='4722**********6', key2='2107', key3=value{value1='226',
value2=passed,value3=tracked, value4=noted}, isChecked=true}";
String data = Datas.substring(5);
//String data1 = data.replaceAll("\"", "");
try {
JSONObject dataObject = new JSONObject((data)); //JsonObject
String strKey1= dataObject.getString("key1");
String strKey2= dataObject.getString("key2");
String strKey3= dataObject.getString("key3");
JSONObject strValueObj = new JSONObject(strKey3);
String strValue1= strValueObj.getString("value1");
String strValue2= strValueObj.getString("value2");
String strValue3= strValueObj.getString("value3");
String strValue4= strValueObj.getString("value4");
Will normal String parsing work or is it correct to parse using JSON? Can anyone please help me on parse the string response.
Well, you could do some data transformations to achive JSON format:
private static final String KEY3 = "key3";
private static final String VALUE = "value";
void extractData() throws JSONException {
String Datas = "Data1{key1='4722**********6', key2='2107', key3=value{value1='226', value2=passed,value3=tracked, value4=noted}, isChecked=true}";
String data = Datas.substring(5);
String dataAsJson = data.replaceAll("=", ":");
if (dataAsJson.indexOf(KEY3) > -1) {
StringBuilder dataBuilder = new StringBuilder(dataAsJson.replaceFirst(VALUE, "{" + VALUE + ":"));
dataBuilder.insert(dataAsJson.indexOf("}", dataAsJson.indexOf(KEY3)) + KEY3.length() - 1, "}");
dataAsJson = dataBuilder.toString();
}
JSONObject dataObject = new JSONObject((dataAsJson));
String strKey1= dataObject.getString("key1");
String strKey3= dataObject.getString("key3");
JSONObject key3Obj = new JSONObject(strKey3);
String value = key3Obj.getString("value");
JSONObject valueObj = new JSONObject(value);
String value1 = valueObj.getString("value1");
}
It works but for sure is not the most elegant solution and might not work if the input would change it's structure.
Edit: new input:
String Datas = "Data1{key1='4722**********6', key2='2107', key3=value{value1='226', value2=passed,value3=tracked, value4=noted}, isMasked=true}";
String data = Datas.substring(5);
String dataAsJson = data.replaceAll("=", ":");
if (dataAsJson.contains(KEY3)) {
StringBuilder dataBuilder = new StringBuilder(dataAsJson.replaceFirst(VALUE, "{" + VALUE + ":"));
dataBuilder.insert(dataAsJson.indexOf("}", dataAsJson.indexOf(KEY3)) + KEY3.length() - 1, "}");
dataAsJson = dataBuilder.toString();
}
JSONObject dataObject = new JSONObject((dataAsJson));
String strKey1 = dataObject.getString("key1");
String strKey3 = dataObject.getString("key3");
JSONObject key3Obj = new JSONObject(strKey3);
String value = key3Obj.getString("value");
JSONObject valueObj = new JSONObject(value);
String value1 = valueObj.getString("value1");
As title said I'm new to JSON and I can't get out of my problem. I'm working on this error for 1 week I'm really desperate to get out.
My error :
JSONException: Value [{"data":"11-13-2017","numeVanzator":"Clau","numarClient":0}] at jsonData of type java.lang.String cannot be converted to JSONArray
My JSON:
{
"jsonData" : {
"11-13-2017" : {
"Clau" : {
"-KyokKjL9UQpsfKZYZqM" : [ {
"pret" : "80",
"produs" : "Shirt",
"produsId" : "-Kyok58s0dOAnVOnbJPk"
} ]
}
}
}
}
I looked over tutorials on StackOverFlow but absolutely no solution.
My code :
private void writeJSON(String metodaPlata) throws JSONException {
String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
String jsonDataFromShared = SharedPreference.getString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");
int totalPrice = 0;
for(VanzatorProduse v : Util.getInstance().getVanzatorProduse())
{
int vPrice = Integer.parseInt(v.getPret());
totalPrice = totalPrice + vPrice;
}
String pretTotal = Integer.toString(totalPrice);
String produseSelectate = Integer.toString(listaProdusePreview.getAdapter().getCount());
JSONObject jsonData;
JSONArray dateJSON;
JSONObject obj;
JSONArray arrayForList;
if (jsonDataFromShared.equals("")) {
jsonData = new JSONObject();
dateJSON = new JSONArray();
obj = new JSONObject();
arrayForList = new JSONArray();
JSONObject objListaSiModalitate = new JSONObject();
// arrayForList.put(stock_list.toString());
objListaSiModalitate.put("lista", new JSONArray(Util.getInstance().getVanzatorProduse()));
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", numarVanzare);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON.toString());
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
} else {
jsonData = new JSONObject(jsonDataFromShared);
dateJSON = jsonData.getJSONArray("jsonData");
obj = new JSONObject();
JSONObject objListaSiModalitate = new JSONObject();
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("produseSelectate", produseSelectate);
obj.put("sumaProduse", pretTotal);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", numarVanzare);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON);
System.out.println("jsonData" + dateJSON);
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
}
}
Please help me I have no idea what to idea even if I look over tutorials.
I think your json parsing will be,
try {
JSONObject jsonObject = new JSONObject("jsonData");
JSONObject jsonObject1 = jsonObject.getJSONObject("11-13-2017");
JSONObject jsonObject2 = jsonObject1.getJSONObject("Clau");
JSONArray jsonArray = jsonObject2.getJSONArray("-KyokKjL9UQpsfKZYZqM");
JSONObject jsonObject3 = (JSONObject) jsonArray.getJSONObject(0);
String string = jsonObject3.getString("pret");
String string1 = jsonObject3.getString("produs");
String string2 = jsonObject3.getString("produsId");
} catch (JSONException e) {
e.printStackTrace();
}
Error causes from this line
jsonData.put("jsonData", dateJSON.toString());
Here dateJSON.toString() store the string value to jsonData variable. jsonData is JsonObject.
Then You try to retrieve JsonArray from string
jsonData = new JSONObject(jsonDataFromShared); //This line convert your string to jsonobject.
dateJSON = jsonData.getJSONArray("jsonData");
EDITED
If you want to retreive array from dateJson object
Replace this line
jsonData.put("jsonData", dateJSON.toString());
To
jsonData.put("jsonData", dateJSON);