What I want to do is at a particular index position change/replace a value inside a json array.After going through the documentation at http://www.json.org/javadoc/org/json/JSONArray.html I found out that jsonArray does not have a getIndex() method.In this situation how do I update my json array at a given index position.
This is the method that creates a json array in my android code.
private void createJsonArray() {
billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
.getText().toString();
String invNumber = textViewInvNo.getText().toString();
String bcode = barCode.getText().toString();
String description = itemDesc.getText().toString();
String wt = weightLine.getText().toString();
String rateAmt = rateAmount.getText().toString();
String making = makingAmount.getText().toString();
String netr = netRate.getText().toString();
String iTotal = itemtotal.getText().toString();
String vatAmt = textViewVat.getText().toString();
String sumAmt = textViewSum.getText().toString();
String crtDate = textViewCurrentDate.getText().toString();
try {
jsonObject.put("custInfo", custSelected.toString());
jsonObject.put("invoiceNo", invNumber);
jsonObject.put("barcode", bcode);
jsonObject.put("description", description);
jsonObject.put("weight", wt);
jsonObject.put("rate", rateAmt);
jsonObject.put("makingAmt", making);
jsonObject.put("net_rate", netr);
jsonObject.put("itemTotal", iTotal);
jsonObject.put("vat", vatAmt);
jsonObject.put("sum_total", sumAmt);
jsonObject.put("bill_type", billType);
jsonObject.put("date", crtDate);
} catch (JSONException e) {
e.printStackTrace();
}
try {
itemSelectedJson.put(index, jsonObject);
index++;
} catch (JSONException e) {
e.printStackTrace();
}
}
And this is the code that I use to update my json array which contains a json object.
try {
itemSelectedJson.getJSONObject(i).put("net_rate",netChange);
Log.d("NETRATE_TW",itemSelectedJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Now the problem with this code is it updates the jsonArray everytime a new item is added to the code.So the first object values are the same as the last object.
Also note that I am using this code inside a text watcher.So the afterTextchanged() method looks like this.
#Override
public void afterTextChanged(Editable s) {
String netChange = netRate.getText().toString();
final int row_id = (int) newRow.getTag();
if ((row_id<0) || (row_id> itemSelectedJson.length())){
return;
}
try {
itemSelectedJson.getJSONObject(row_id-1).put("net_rate",netChange);
Log.d("NETRATE_TW",itemSelectedJson.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
};
This is the snapshot of what my database looks like.
A jSONObject(which is a collection of name,value pairs) can be converted into a JSONArray which is an ordered array of the "values" in the JSONObject.
This can be done using the .toJSONArray() method.
When you need to replace/update the JSONArray, you may use the method
.put(int index, java.util.Map value)
Unlike how you are doing at present, i.e getting the object and setting a new key and value.
http://www.json.org/javadoc/org/json/JSONArray.html#put(int, java.util.Map)
As I understood, your problem is in creating multiple JSONObjects in your JSONArray with the same values, and that's because you can't get the index of a created JSONObject inside your JSONArray, and to overcome this problem, you can easily create a compound JSONObject that contains your JSONObjects instead of a JSONArray contains JSONObjects, and the object name will be anything unique in your JSONObject data, and when you make any changes or add any item it will either be added as a new object if it doesn't exist or it will overwrite the existing object if it added before, for example let's suppose that barcode value is unique in your data, so the code will be like the following:
// declaring itemSelectedJson as JSONObject
JSONObject itemSelectedJson = new JSONObject();
.
.
.
// when wanting to add a new item
itemSelectedJson.put(jsonObject.getString("barcode"), jsonObject);
and to retrieve the data you simple iterate through this JSONObject:
Iterator<?> keys = itemSelectedJson.keys();
JSONObject single_item;
while(keys.hasNext()) {
String key = (String)keys.next();
single_item = itemSelectedJson.getJSONObject(key);
// do what do you want here
}
Related
So basically I'm trying to remove some part of my list, but the problem is because I just got into android development, I don't know the format of the list that I got from JSON file.
Here is the code of my method that retrieve it from a JSON file:
public void getCategory (JSONArray jsonArray, List<ModelCategory> Category){
for (int i = 0; i < jsonArray.length(); i++){
try {
ModelCategory currentCategory = new ModelCategory();
JSONObject jsonObject = jsonArray.getJSONObject(i);
currentCategory.setCategoryID(jsonObject.getInt("idCategory"));
currentCategory.setCategoryName(jsonObject.getString("name"));
Category.add(currentCategory);
kat1.addAll(Category);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Basically, I'm trying to remove the idCategory from the kat1 list. But I don't know what the list looks like. I've read about remove() method from the list, but how do I utilize the method to remove the idCategory?
I'm sorry for the unclear title, I'm pretty new to java development.
I need to write a code which would convert JSON file to CSV. The problem is in a format that the CSV file should look like.
Input json:
{
"strings":{
"1level1":{
"1level2":{
"1label1":"1value1",
"1label2":"1value2"
}
},
"2level1":{
"2level2":{
"2level3":{
"2label1":"2value1"
},
"2label2":"2value2"
}
}
}
}
And this is expected csv file for this json:
Keys,Default
1level1.1level2.1label1,1value1
1level1.1level2.1label2,1value2
2level1.2level2.2level3.2label1,2value1
2level1.2level2.2label2,2value2
I was trying to go through JSON file using recursion but this didn't work for me because of rewriting JSON object on each iteration and code was working only till the first value. Are there any suggestions about how can it be done?
Note: have tried to use different JSON libraries, so for now can be used any of them
UPDATE #1:
Non-working code example I was trying to use to go through JSON tree:
public static void jsonToCsv() throws JSONException {
InputStream is = MainClass.class.getResourceAsStream("/fromJson.json");
JSONTokener jsonTokener = new JSONTokener(is);
JSONObject jsonObject = new JSONObject(jsonTokener);
stepInto(jsonObject);
}
private static void stepInto(JSONObject jsonObject) {
JSONObject object = jsonObject;
try {
Set < String > keySet = object.keySet();
for (String key: keySet) {
object = object.getJSONObject(key);
stepInto(object);
}
} catch (JSONException e) {
Set < String > keySet = object.keySet();
for (String key: keySet) {
System.out.println(object.get(key));
}
e.printStackTrace();
}
}
UPDATE #2:
Another issue is that I will never know the names of the JSON object and count of child objects (update JSON and CSV examples as well to make the image more clear). All that is known, that it will always start with strings object.
Library used:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
So found a solution by myself:
public static void jsonToCsv() throws JSONException, IOException {
InputStream is = MainClass.class.getResourceAsStream("/fromJson.json");
JSONTokener jsonTokener = new JSONTokener(is);
JSONObject jsonObject = new JSONObject(jsonTokener).getJSONObject("strings");
builder = new StringBuilder();
while (!jsonObject.isEmpty()) {
stepInto(jsonObject);
}
String[] lines = builder.toString().split("\n"); // builder lines are in reverse order from expected so this array is used to reverse them
FileWriter csvWriter = new FileWriter("src/main/resources/toCsv.csv");
csvWriter.append("Keys,Default (en_US)\n");
for (int i = lines.length - 1; i >= 0; i--) {
csvWriter.append(lines[i]).append("\n");
}
csvWriter.flush();
csvWriter.close();
}
private static void stepInto(JSONObject jsonObject) {
for (String key: jsonObject.keySet()) {
Object object = jsonObject.get(key);
if (object instanceof JSONObject) {
builder.append(key).append(".");
stepInto(jsonObject.getJSONObject(key));
} else {
builder.append(key).append(",").append(object).append("\n");
jsonObject.remove(key);
break;
}
if (jsonObject.getJSONObject(key).isEmpty()) {
jsonObject.remove(key);
}
break;
}
}
I think you just missed keeping track of your result, otherwise it looks good.
Let's say your result is a simple string. Then you have to concatenate all keys while traversing the json object until you reach a primitive value (like a number or a string).
(I am writing this out of my head, so please forgive me for incorrect syntax)
private static String stepInto(JSONObject jsonObject) { // we change "void" to "String" so we can record the results of each recursive "stepInto" call
//JSONObject object = jsonObject; // we don't need that. Both variables are the same object
String result ="";
try {
for (String key: jsonObject.keySet()) { // shorter version
Object object = jsonObject.get(key); // Attention! we get a simple Java Object
if(object instanceof JSONObject){
result+= key+"."+stepInto(jsonObject.getJSONObject(key)); // the recursive call, returning all keys concatenated to "level1.level2.level3" until we reach a primitive value
}
if(object instanceof JSONArray){
result+= key+", "+ ... // notice how we use the csv separator (comma) here, because we reached a value. For you to decide how you want to represent arrays
}
result+= key +", "+ object +"\n"; // here I am not sure. It may well be that you need to check if object is a String an Integer, Float or anything.
}
} catch (JSONException e) {
for (String key: jsonObject.keySet()) {
System.out.println(object.get(key));
}
e.printStackTrace();
result+= "\n"; // I added this fallback so your program can terminate even when an error occurs.
}
return result; // sorry, I forgot to accumulate all results and return them. So now we have only one actual "return" statement that will terminate the call and return all results.
}
As you can see, I didn't change much of your original method. The only difference is that now we keep track of the keys ("level1.level2...") for each recursive call.
EDIT
I added a +"\n"; so everytime we reach a value so we can terminate that "line".
AND more importantly, instead of returning everytime, I add the result of each call to a string, so we continue looping over the keys and concatenate all results. Each call of the method will return only once all keys are looped over. (sorry that missed that)
In your calling method you could print out the result, something like that:
JSONObject jsonObject = new JSONObject(jsonTokener);
String result = stepInto(jsonObject);
System.out.println(result);
I have the json array :
{"objets":{"1":"Question","2":"Response"},"success":true}
I want to test if the text selected on spinner exist in the array it will return the number (1 or 2).
Here is what I've done until now :
String responseContent = response.asString();
Log.d("OBJECTS", responseContent);
try {
JSONObject jobj = new JSONObject(responseContent);
JSONObject users = jobj.getJSONObject("objetcs");
Log.e("hello", String.valueOf(users));
if(users.toString().contains(spinner_objet.getSelectedItem().toString().trim())){
Log.e("hello", "it exist");
String user=users.getString("id");
Log.e("hello1", String.valueOf(user));
}
} catch (JSONException e1) {
e1.printStackTrace();
}
But I'm not getting any thing, can any one help me with this ?
You can parse your Json into a hashMap like so :
JSONObject object = new JSONObject();
Map<String,Integer> map = new HashMap<>();
while (object.keys().hasNext() ){
Integer key = (Integer) object.keys().next();
map.put((String) object.get(String.valueOf(key)), key);
}
You can then use the values of the map to put in the spinner.
map.values();
Whenever the user selects from the spinner, you can get the id from the map.
My problem is simple, I'd like to add a JSONObject to a JSONArray that I store in a MongoDB database. I can easily add all types of data like Strings, Ints etc but not JSONObjects.
I do this in my code :
public void done(ParseObject lan, ParseException e) {
if(e==null){
JSONObject object = new JSONObject();
try{
object.put("PlayerName","John");
object.put("ID",514145);
lan.add("Participants",object); //nothing gets inserted
lan.add("Participants",15); //works fine
lan.add("Participants",JSONObject.null); //works fine too
}catch (JSONException error){
}
lan.increment("Number");
lan.saveInBackground();
}else{
Log.i("Parse Error","error");
}
}
But nothing appears in my db and there's no error thrown.
Do you guys have any clue on how to do that ?
Try using object.toString() instead of object.
lan.add("Participants", object.toString());
JSON:
{"Participants":["{\"PlayerName\":\"John\",\"ID\":514145}"]}
To parse this JSON try this:
JSONObject jsonObj = new JSONObject(YOUR_JSON_STRING);
// Participants
JSONArray participantsJsonArray = jsonObj.getJSONArray("Participants");
// Participant
JSONObject participanJsonObject = participantsJsonArray.getJSONObject(0);
// PlayerName
String playerName = participanJsonObject.getString("PlayerName");
// ID
String id = participanJsonObject.getInt("ID");
Hope this will help~
Convert that Json Object into String and store it in string format
lan.add("Participants",object.toString());
And when you want to use that you can easily convert it into Json Object again like this
JSONObject jObj=new JSONObject("Your Json String");
I'm very new to Java and trying to find and check whether a particular value exists in JSON object. Here is my code,
String strUsers = representation.getText();
JSONObject jsonObject = new JSONObject(strUsers);
Iterator<String> keys = jsonObj.keys();
while(keys.hasNext()) {
String key = keys.next();
String val = null;
try {
JSONObject value = jsonObj.getJSONObject(key);
} catch(Exception e) {
}
}
Further I'm not able to understand how to check. Can any one guide me in achieving my goal?
You should use the method has.
if(jsonObject.has("your_key")) {
// get the value and do something with it
}
In your try-catch block, before getting the value check if the key actually exists.
if (jsonObject.has(key)) {
// then get the value
JSONObject value = jsonObj.getJSONObject(key);
}