How to Parse the given JSON Specially Which contains Array using ObjectMapper - swift3

import Foundation
import ObjectMapper
class MemberActivityCollection: Mappable
{
var TotalRows : Int = 0
var MemberActivityList : Array<MemberActivity> = Array()
var MemberID: Int = 0
init(){ }
internal required init?(map: Map) { }
// Mappable
func mapping(map: Map) {
MemberActivityList <- map["MemberActivityList"]
TotalRows <- map["TotalRows"]
MemberID <- map["MemberID"]
}
}
class MemberActivity: Mappable
{
var ActivityID: Int = 0
var fk_MemberID: Int = 0
var ActivityDate: String!
var ActivityFrom: String!
var ActivityTo: String!
var AvgPace: String!
init(){ }
internal required init?(map: Map) { }
// Mappable
func mapping(map: Map) {
ActivityID <- map["ActivityID"]
fk_MemberID <- map["fk_MemberID"]
ActivityDate <- map["ActivityDate"]
ActivityFrom <- map["ActivityFrom"]
ActivityTo <- map["ActivityTo"]
AvgPace <- map["AvgPace"]
}
}
Please Note : The MemberActivityCollection Class has Array of MemberActivity Class
Need to Parse the JSON as MemberActivityCollection
{
"TotalRows" : 16,
"MemberActivityList" : [
{
"fk_MemberID" : 47,
"ActivityID" : 29,
"ActivityFrom" : "18:30:00",
"ActivityTo" : "14:30:00",
"AvgPace" : "3.00"
},
{
"fk_MemberID" : 47,
"ActivityID" : 26,
"ActivityFrom" : "01:07:46",
"ActivityTo" : "05:07:00",
"AvgPace" : "5.00"
},
{
"fk_MemberID" : 47,
"ActivityID" : 35,
"ActivityFrom" : "09:30:00",
"ActivityTo" : "04:15:00",
"AvgPace" : "0.06"
}
],
"MemberID" : 47
}
Using the following code to map the json to object of MemberActivityCollection Class
Am I declaring the property MemberActivityList wrong way??
The whole idea is to map the json in MemberActivityCollection class so that one of its property ("MemberActivityList") can hold the detailed data
To Achieve that I wrote following lines of code and not getting the desired output (As mentioned in the above line).
let objMAC : MemberActivityCollection = Mapper<MemberActivityCollection>().map(JSONObject: jsonData)! //Datatype of jsonData variable is JSON
The above statement throws error message that 'EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0'
Please explain the correct way to achieve this.

Related

libbson help to read data into object C++

i have my unreal project that must read out some BSON document data into a map.
right now i'm able to load that file and print it out with the following code :
void AMyActor::BeginPlay()
{
Super::BeginPlay();
std::ifstream input( filePath , std::ios::binary );
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
bson_t* doc{ bson_new_from_data(buffer.data(),buffer.size()) };
char *str;
if( doc != nullptr )
{
UE_LOG(LogTemp,Warning,TEXT( "Success" ));
str = bson_as_json(doc, NULL);
FString fstr = FString(UTF8_TO_TCHAR(str));
UE_LOG(LogTemp, Warning, TEXT("BSON Output: %s"), *fstr);
}
}
and this is here is where i want to store it :
class Databases
{
std::map<std::string,DatabaseBase> _dictionary;
explicit Databases(const std::map<std::string, DatabaseBase>& dictionary)
: _dictionary(dictionary)
{
}
};
so what i'm looking for is to create a new instance of Databases and initialize "_dictionary" with the content of the bson document.
i'm actually looking for this into the libbson document : http://mongoc.org/libbson/current/bson_t.html
but without success...anyone can help me?
thank's in advance
PS: i'm under unreal but i have linked the libbson library
Update:
since i have to provide how my json file looks like, and DatabaseBase looks like
JSON :
{
"_dictionary" : [ {
"_classID" : "CC00",
"_dictionary" : [ {
"k" : "sample_key",
"v" : ["ACH_00"]
}, {
"k" : "sample_index",
"v" : ["0"]
}]
}, {
"_classID" : "CC01",
"_dictionary" : [ {
"k" : "sample_key",
"v" : ["ACH_01"]
}, {
"k" : "sample_index",
"v" : ["1"]
}]
}]
}
DatabaseBase :
class DatabaseBase
{
public:
DatabaseBase() = default;
std::string sample_key;
int sample_index;
};
Breaking out nlohmann::json:
using nlohmann::json;
std::map<std::string, DatabaseBase> dictionaries;
json input = json::from_bson(buffer);
for (auto& obj : input["_dictionary"]) {
auto name = obj["_classID"];
auto key = obj["_dictionary"][0]["v"][0];
auto idx = stoi(obj["_dictionary"][1]["v"][0].get<std::string>());
auto db = DatabaseBase{key, idx};
dictionaries[name] = db;
}
Databases dbs{dictionaries};
output: (from my debugger)
(lldb) p dbs
(Databases) $0 = {
_dictionary = size=2 {
[0] = {
first = "CC00"
second = (sample_key = "ACH_00", sample_index = 0)
}
[1] = {
first = "CC01"
second = (sample_key = "ACH_01", sample_index = 1)
}
}
}

How to convert a MAP into a LIST in DART?

i'm having trouble to convert a MAP into a LIST on DART.
Here is how my code looks like:
try {
var response = await http.get(url, headers: header);
List listaResponse = jsonDecode(response.body);
final lockers = <Locker>[];
for (Map map in listaResponse) {
Locker l = Locker.fromJson(map);
lockers.add(l);
}
return lockers;
} catch (e) {
print("error in api ");
print(e);
}
This is the output error:
I/flutter (14625): type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
And this is how my json looks like:
{
meus_testes_vw: [
{
id_teste = 73,
otherinfo = ahsuasa
........
},
{
id_teste = 74,
........
}
]
}
Your JSON Data is not a List<Map<String, dynamic>> but a Map<String, List<Map<String, dynamic>>>: { 'meus_testes_vw': [...] }.
Try to change the assignment of your listaResponse:
List listaResponse = jsonDecode(response.body)['meus_testes_vw'];

Retrieving data from Firebase (Realtime Database) into a list (Kotlin)

The RealtimeDatabase structure in Firebase
I want to go over the entire users in "mifkada" and to add them into a list as a BlogPost object:
class BlogPost (
var namerv: String,
var gafrv: String,
var placerv: String,
var phonerv: String,
var notesrv: String
) {
constructor() : this("", "", "", "", "") {}
}
I tried to do it with a for loop but it doesn't work the way I wrote it
class DataSource{
companion object{
fun createDataSet(): ArrayList<BlogPost>{
var databaseMifkada = FirebaseDatabase.getInstance().getReference("mifkada")
val list = ArrayList<BlogPost>()
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot!!.exists()){
list.clear()
for (e in dataSnapshot.children){
val post = e.getValue(BlogPost::class.java)
list.add(post!!)
}
}
}
override fun onCancelled(databaseError: DatabaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
}
}
databaseMifkada.addValueEventListener(postListener)
return list
}
}
}
The values of your constructor does not match the names of your database values
class BlogPost (
var namerv: String,
var gafrv: String,
var placerv: String,
var phonerv: String,
var notesrv: String
) {
constructor() : this("", "", "", "", "") {}
}
Should be
class BlogPost (
var name: String,
var gaf: String,
var place: String,
var phone: String,
var notes: String
) {
constructor() : this("", "", "", "", "") {}
}
You need to have the same name because when you do
val post = e.getValue(BlogPost::class.java)
it will look for those field names under the reference, and if it can't be reached, you can't get those values

raw Value of optional type not unwrapped

I am trying to unwrap the raw value of an enum type in func toDictionary() , but I get an error.
How can I fix this?
enum ChatFeatureType: String {
case tenants
case leaseholders
case residents
}
class Chat {
var featureType: ChatFeatureType?
init(featureType: ChatFeatureType? = nil
self.featureType = featureType
}
//download data from firebase
init(dictionary : [String : Any]) {
featureType = ChatFeatureType(rawValue: dictionary["featureType"] as! String)!
}
func toDictionary() -> [String : Any] {
var someDict = [String : Any]()
// I get error on the line below: Value of optional type 'ChatFeatureType?' not unwrapped; did you mean to use '!' or '?'?
someDict["featureType"] = featureType.rawValue ?? ""
}
}
As featureType is an optional you have to add ? or ! as the error says
someDict["featureType"] = featureType?.rawValue ?? ""
But be aware that your code reliably crashes when you create an instance of Chat from a dictionary and the key does not exist because there is no case "".
Actually the purpose of an enum is that the value is always one of the cases. If you need an unspecified case add none or unknown or similar.
This is a safe version
enum ChatFeatureType: String {
case none, tenants, leaseholders, residents
}
class Chat {
var featureType: ChatFeatureType
init(featureType: ChatFeatureType = .none)
self.featureType = featureType
}
//download data from firebase
init(dictionary : [String : Any]) {
featureType = ChatFeatureType(rawValue: dictionary["featureType"] as? String) ?? .none
}
func toDictionary() -> [String : Any] {
var someDict = [String : Any]()
someDict["featureType"] = featureType.rawValue
return someDict
}
}

MongoDB Map Reduce C#

I am currently doing a map-reduce with the c# driver in Mongo.
I have got it working where the JSON is as follows:
{ "_id" : CSUUID("ef53b163-699c-462f-9135-b81bad115635"), "value" : { "firstname" : "Joe", "lastname" : "Bloggs", "groupName" : "System Wide Access" } }
What I want to do is flatten this object so as I don't have an Id and Value field, I only want the actual properties that are in my read model class.
Here is my code as it is currently:
const string mapUserGroupMember = #"function ()
{
var output = {groupId:this.GroupId, firstname:this.Forename, lastname:this.Surname, groupName:null}
emit(this.GroupId, output);
}";
const string mapUserGroupName = #"function ()
{
var output = {groupId:this._id, firstname:null, lastname:null, groupName:this.Name}
emit(this._id, output);
}";
var reduceF = #"function(key, values) {
var results = {firstname:null, lastname:null , groupName:null};
values.forEach(function(v){
if(results.firstname ==null){
results.firstname = v.firstname
}
if(results.lastname ==null){
results.lastname = v.lastname
}
if(results.groupName ==null){
results.groupName = v.groupName
}
});
return results;
};";
var groupMemberCollection = database.GetCollection("UserGroupMemberReadModel");
var groupNameCollection = database.GetCollection("UserGroupNameReadModel");
var options = new MapReduceOptionsBuilder();
options.SetOutput(MapReduceOutput.Reduce("MergedData"));
var results = groupNameCollection.MapReduce(mapUserGroupName, reduceF, options);
results = groupMemberCollection.MapReduce(mapUserGroupMember, reduceF, options);
I want to be able to call var collection = database.GetCollection("MergedData").AsQueryable<ReadModel>();
Any help would be appreciated.