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!
Related
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]
}
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
I want to create an empty array in Firestore while posing a feed. But the array is showing null in Firestore. Here is my code. Please help.
class FeedModel {
final String imgUrl;
final String desc;
final String authorName;
final String profileImg;
final String title;
final int likeCount;
List<String> strArr = []; // this the array i want to create it in firestore
FeedModel({this.imgUrl, this.desc,this.authorName,this.profileImg,this.title,this.likeCount, this.strArr});
Map<String, dynamic> toMap(){
return {
"imgUrl" : this.imgUrl,
"desc" : this.desc,
"authorName" : this.authorName,
"profileImg" : this.profileImg,
"like_count" : this.likeCount,
"liked_user_id" : this.strArr
};
}
}
Here is the send data code:
Future<void> _sendData() async {
try {
final StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child('myimage.jpg');
final StorageUploadTask task = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await task.onComplete;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
final String pname = myController.text;
final String pimgurl = downloadUrl;
final String pauthorName = "Sachin Tendulkar";
final String pprofileImg = "https://i.picsum.photos/id/564/200/200.jpg?hmac=uExb18W9rplmCwAJ9SS5NVsLaurpaCTCBuHZdhsW25I";
final String ptitle = "Demo Data";
final int plikeCount= 0;
List<String> pLikeduserId; // This line returning null as show in image
print(pimgurl);
final FeedModel feeds = FeedModel(imgUrl: pimgurl ,desc: pname,authorName: pauthorName ,profileImg: pprofileImg,title: ptitle,likeCount: plikeCount, strArr : pLikeduserId );
insertData(feeds.toMap());
} catch (e) {
print(e);
}
}
null image:
want to get like below image:
How can i send array like last image when creating a feed?
If you want an array in a field, even an empty array, you will have to assign it an actual list value. Right now, by not assigning any actual list value at all, you're effectively assigning a null value to the liked_user_id.
So, just give it a value:
List<String> pLikeduserId = [];
That will write an empty list field.
There isn't much of a reason to store it as an array with a value of ''. Instead, it would be better to null check when receiving the value from firebase by using something like: liked_userid = /*insert method of getting firebase user ID*/??[]
This way when you use the liked_userid it won't be null and will be an empty list.
If you really want a list with the value of '' inside than change the insides of the toMap function:
Map<String, dynamic> toMap(){
return {
"imgUrl" : this.imgUrl,
"desc" : this.desc,
"authorName" : this.authorName,
"profileImg" : this.profileImg,
"like_count" : this.likeCount,
"liked_user_id" : this.strArr=[]?['']:this.strArr//line that was changed
};
}
This would make it so that you will have an array with [''] inside but I would still recommend the first method I showed.
Do this to create an array with an empty string.
Map<String, dynamic> toMap() {
return {
'liked_user_id': List.generate(1, (r) => "")
};
}
await _fireStore.collection("COLLECTION_NAME").document("DOUCUMENT_NAME").setData({
"KEY_VALUE": [],
});
This creates an empty Array in Cloud FireStore.
I'm trying to send a Map<String, dynamic>, and one of the dynamic is actually a List<Map<String, dynamic>>.
I assemble it like that :
Packet packet = Packet(
datas: stocks.map((stock) => stock.toJson()).toList(),
);
String json = jsonEncode(packet);
The problem is what's being sent is actually this :
{
"datas": {
"rows": "[{NoArticle: 051131626638, Description: Ruban pour tapis, qty: 5}]"
}
}
The expected output is this :
{
"datas": {
"rows": [{
"NoArticle": "051131626638",
"Description": "Ruban pour tapis",
"qty": 5,
}]
}
}
I want to send a List<Map<String, dynamic>>, not a String. How do I do that?
Answer : I am a dumbass.
I passed the parameter trough a function, like this :
Server.send("sendInventoryBatch", {
"rows": "${stocks.map((stock) => stock.toJson()).toList()}",
});
Of course it would return a String.
Question is invalid. If you have a similar problem, please open a different question. Sorry for the inconvenience.
Now if anyone actually has this question and stumbles upon this thread, here's how to do it :
Assemble your object, and make sure you didn't stringify it along the way
Use jsonEncode
In case of doubt, make everything a Map<String, dynamic>, a List<dynamic>, or a sub-class of those two first.
Packet packet = Packet(
appType: "inventoryManager",
module: "",
action: action,
datas: data,
deviceID: Globals.map["UUID"],
cbackid: cback,
);
You can generate classes like my custom Packet from JSON using multiple online resources because jsonEncode will use the auto-generated Map<String, dynamic> toJson().
https://app.quicktype.io/ - Was recommended to me on Discord by Miyoyo#5957
https://javiercbk.github.io/json_to_dart/ - I used this one before
http://json2dart.com/
String json = jsonEncode(packet);
And voilĂ , you're done.
Did you look at packages json_serializable?
Here's an example of a Person that has many Orders : example
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:json_annotation/json_annotation.dart';
part 'example.g.dart';
#JsonSerializable()
class Person {
final String firstName;
#JsonKey(includeIfNull: false)
final String middleName;
final String lastName;
#JsonKey(name: 'date-of-birth', nullable: false)
final DateTime dateOfBirth;
#JsonKey(name: 'last-order')
final DateTime lastOrder;
#JsonKey(nullable: false)
List<Order> orders;
Person(this.firstName, this.lastName, this.dateOfBirth,
{this.middleName, this.lastOrder, List<Order> orders})
: orders = orders ?? <Order>[];
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
#JsonSerializable(includeIfNull: false)
class Order {
int count;
int itemNumber;
bool isRushed;
Item item;
#JsonKey(
name: 'prep-time',
fromJson: _durationFromMilliseconds,
toJson: _durationToMilliseconds)
Duration prepTime;
#JsonKey(fromJson: _dateTimeFromEpochUs, toJson: _dateTimeToEpochUs)
final DateTime date;
Order(this.date);
factory Order.fromJson(Map<String, dynamic> json) => _$OrderFromJson(json);
Map<String, dynamic> toJson() => _$OrderToJson(this);
static Duration _durationFromMilliseconds(int milliseconds) =>
Duration(milliseconds: milliseconds);
static int _durationToMilliseconds(Duration duration) =>
duration.inMilliseconds;
static DateTime _dateTimeFromEpochUs(int us) =>
DateTime.fromMicrosecondsSinceEpoch(us);
static int _dateTimeToEpochUs(DateTime dateTime) =>
dateTime.microsecondsSinceEpoch;
}
#JsonSerializable()
class Item {
int count;
int itemNumber;
bool isRushed;
Item();
factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json);
Map<String, dynamic> toJson() => _$ItemToJson(this);
}
#JsonLiteral('data.json')
Map get glossaryData => _$glossaryDataJsonLiteral;
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".