How to parse mulitple Json Arrays with the same name in Android - arrays

I want to parse a Json File where all Json Arrays have the same Name:
[
{
"mobileMachine":{
"condition":"GOOD",
"document":"a",
"idNr":"ce4f5a276a55023efced9c6a4b02bf4fcff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e"
}
},
{
"mobileMachine":{
"condition":"GOOD",
"document":"b",
"idNr":"ce4f5a276a8e023efced9c6a4b02bf4fcff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb217e"
}
},
...
]
So here is my little Code:
JSONArray json = new JSONArray(urlwhereIGetTheJson);
for (int count = 0; count < json.length(); count++) {
JSONObject obj = json.getJSONObject(count);
String condition = obj.getString("condition");
String document = obj.getString("document");
String idNr = obj.getString("idNr");
db.addMachine(new MachineAdapter(condition, document, idNr));
}
I hope u can show me how to parse the JSON File correctly. Thank you
I can't edit the JSON File. (The File include more than 300 mobilemachines. I have shorten this).
(Sorry for my English)

Edit: You are using the new JSONArray() constructor incorrectly. Have a look at the documentation. You can not directly pass the url there. You have to obtain it first, and then pass the json to the constructor.
The following piece of code does what you want to do:
JSONArray jsonArray = new JSONArray(json);
int numMachines = jsonArray.length();
for(int i=0; i<numMachines; i++){
JSONObject obj = jsonArray.getJSONObject(i);
JSONObject machine = obj.getJSONObject("mobileMachine");
String condition = machine.getString("condition");
String document = machine.getString("document");
String idNr = machine.getString("idNr");
db.addMachine(new MachineAdapter(condition, document, idNr));
}
You forgot to obtain the "mobileMachine" json object, and tried to access condition/document/idNr directly.
If you have control over the XML, you could make it smaller by removing the "mobileMachine" node:
[
{
"condition":"GOOD",
"document":"a",
"idNr":"ce4f5a276a55023efced9c6a4b02bf4fcff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e"
},
{
"condition":"GOOD",
"document":"b",
"idNr":"ce4f5a276a8e023efced9c6a4b02bf4fcff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb217e"
},
...
]

Change it to
JSONArray json = new JSONArray(jsonString);
for (int count = 0; count < json.length(); count++) {
JSONObject obj = json.getJSONObject(count).getJSONObject("mobileMachine");
String condition = obj.getString("condition");
String document = obj.getString("document");
String idNr = obj.getString("idNr");
db.addMachine(new MachineAdapter(condition, document, idNr));
}
You forgot "mobileMachine".

Related

How to iterate JSON objects

How can I iterate a json object and get it's values in dart.
Below is an Example json object that is want to get it's value.
"SomeJsonList": {
"image": ["imageUrl1", "imageUrl2"],
"video": ["videoUrl1", "videoUrl2"]
}
To get the values of the image and video object as a list.
The output i am looking for:
var urlList = [];
urlList = [imageUrl1, imageUrl2,videoUrl1,
videoUrl2]
You can merge list items using addAll as below
void main() {
Map<String, List<String>> json = {
"image": ["imageUrl1", "imageUrl2"],
"video": ["videoUrl1", "videoUrl2"]
};
List<String>? img = json["image"];
List<String>? vid = json["video"];
List<String> list = [];
list.addAll(img!); // better check if `img` not null instead of "!"
list.addAll(vid!); // better check if `vid` not null instead of "!"
// list.addAll(xyz); // some more if needed
print(list); // [imageUrl1, imageUrl2, videoUrl1, videoUrl2]
}

How To Get Json object inside json object

My code snippet for nested json object:
JsonArray arr = jsonObject.getAsJsonArray("data");
for(int i = 0; i < arr.size(); i++) {
String _Id = arr.get(i).getAsJsonObject().get("_id").getAsString();
String Name = arr.get(i).getAsJsonObject().get("name").getAsString();
int Trips = arr.get(i).getAsJsonObject().get("trips").getAsInt();
}
You can parse JSON using JSON.parse();
let exampleJSON = '{ "id": 245, "name": "Mike" }';
const obj = JSON.parse(exampleJSON);
console.log(obj.id); // 245

loop to create array of arrays of same-length strings

I'm trying to create an array of arrays that are grouped according to their lengths (strings), such that the array below:
var testA = ["carts","carts","cars","cars","ca","ca", "ca","a","a","a","a"];
would become:
var sortedArrays = [["carts","carts"], ["cars","cars"],["ca","ca","ca"], ["a","a","a","a"]]
I am currently trying the loop below but simply cannot get this to work. I know it'll be something simple, but I've spent so long trying to complete this with no that it's proving incredibly frustrating.
var testA = ["carts","carts","cars","cars","ca","ca", "ca","a","a","a","a"];
var sortedArrays = [];
for(i=0; i < testA.length; i++){
longestWord = 0;
wordHolder = []
wordHolder.push(testA[i])
if (testA[i].length > longestWord){
longestWord = testA[i].length
wordHolder.push(testA[i])
}
sortedArrays.push(wordHolder)
}
Any help will be greatly appreciated
What about the following code (Swift, but it should be easy to reformulate it in other languages):
let testA = ["carts","carts","cars","cars","ca","ca", "ca","a","a","a","a"]
var maxLength = 0
for string in testA {
if string.count > maxLength { maxLength = string.count }
}
var sortedArrays: [[String]] = []
for nextLength in 0 ... maxLength {
let invertedLength = maxLength - nextLength
let nextArray = testA.filter { $0.count == invertedLength }
sortedArrays.append(nextArray)
}
This code creates also empty arrays, which can of course easily be skipped.
The question, of course, is what your requirements are. The code above is compact, but it is not fast for large arrays...
For large arrays, it would be better, first to sort testA, and then to extract the elements.
Sticking with java script, I was able to do the following. My assumption is the words are already sorted descending by length and that there is only one word of each length. That's based on what you were doing. I think what was going on is that too much was getting initialized or reset each time through the loop.
var testA = ["carts", "carts", "cars", "cars", "ca", "ca", "ca", "a", "a", "a", "a"];
var sortedArrays = [];
var wordHolder = []; // took outside loop to ensure initialized
var curLength = testA[0].length;// assuming here that testA not empty
for (var i = 0; i < testA.length; i++) {
if (testA[i].length === curLength) { // more of the same
wordHolder.push(testA[i]);
} else { // new block starts
curLength = testA[i].length;
sortedArrays.push(wordHolder);
// alert (wordHolder)
// alert (sortedArrays)
wordHolder = [];
wordHolder.push(testA[i]);
}
}
sortedArrays.push(wordHolder);// add the last one

I cannot modify the dictionary value when enumerating an array consist of dictionary elements

var files = NSMutableArray()
...
for (var i = 0; i < files.count; i++) {
var f = files[i] as [String: AnyObject]
f["selected"] = true
}
When I debug the code, the "selected" property of f is set correctly. but the corresponding element in the files remains unchanged. Why? Thanks.
I am not sure what is going on with using an NSMutableArray here... but perhaps it's working like a value type instead of a reference type. Try replacing the item in the array with the modified version.
files.replaceObjectAtIndex(i, withObject: f)
Place it after you make your modification.
var files = NSMutableArray()
//...
for (var i = 0; i < files.count; i++) {
var f = files[i] as! [String: AnyObject]
f["selected"] = true
files.replaceObjectAtIndex(i, withObject: f)
}
If you were using a swift array type, something like this should work instead.
var files = [[String: AnyObject]]()
//...
for (var i = 0; i < files.count; i++) {
var f = files[i] as [String: AnyObject]
f["selected"] = true
files[i] = f;
}
The reason corresponding elements of file is not changing is that you are not modifying it at all you are just altering values of var f inside the loop.
Try this code:
var files = [Dictionary<String,AnyObject>]()
// Probably you are trying to make array of dictionary objects
for var i = 0; i < 10 ; i++ {
files[i]["selected"] = true
}

How do I select an item from a json using codenameone Result?

I have this JSON
"DocumentType": {
"propertyName": "DocumentType",
"propertyType": "Text",
"propertyValue": "Fire"
},
"adsfsadf": {
"propertyName": "adsfsadf",
"propertyType": "Text",
"propertyValue": "sfsfdffsd"
}
I want to search and retrieve the node that has propertyName="DocumentType"? I have tried
result.get("//#propertyName='DocumentType'/..")
And also tried
result.get("//propertyName[text()='DocumentType'/..")
And get a null object each time.
Try the following code
JSONParser p = new JSONParser();
Map<String, Object> myMap = p.parseJSON(new InputStreamReader(YOUR JSON INPUT STREAM));
ArrayList<Map<String, String>> myList = (ArrayList<Map<String,String>>)myMap.get("DocumentType");
for (int i = 0; i < myList.size(); i++) {
Map<String, String> dtls = myList.get(i);
String prop = dtls.get("propertyName"));
}
Thanks!

Resources