parse an array as a Json string using DataContractJsonSerializer WP7 - arrays

How can I parse the elements of an array in a Json string using DataContractJsonSerializer?
The syntax is:
{
"array":[
{
"elementsProperies":"SomeLiteral"
}
]
}

You wouldn't necessarily "parse" a json string using DataContractJsonSerializer, but you can deserialize it into an object or list of objects using this. Here is a simple way to deserialize it to a list of objects if this is what you're after.
First you need to have an object type you plan on deserializing to:
[DataContract]
public class MyElement
{
[DataMember(Name="elementsProperties")] // this must match the json property name
public string ElementsProperties { get; set; }
}
You can then use something like the following method to deserialize your json string to a list of objects
private List<MyElement> ReadToObject(string json)
{
var deserializedElements = new List<MyElement>();
using(var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var ser = new DataContractJsonSerializer(deserializedElements.GetType());
deserializedElements = ser.ReadObject(ms) as List<MyElement>;
}
return deserializedUsers;
}

I suggest using Json.net.
In it you would just call:
var jsonObj = JObject.Parse(yourjsonstring);
var elPropertyValue = (string)jsonObj.SelectToken("array[0].elementsProperies");
to get the "SomeLiteral".

Related

Create an empty array and send it to Firestore with an empty value in Flutter?

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.

Circe: Json object to Custom Object

I've go this json node
...
"businessKeys": [
"product://color?product_code",
"product://?code"
]
...
after a sequence of computation I have a Json istance but I'm not able to understand how I can transform that object into a List of my object. So Json (istance) to List[MyClass].
MyClass(root: ParameterType, children: List[ParameterType] = List.empty)
ParameterType(parameter: String)
I have a method that transform a String into a MyClass istance, so I need to decode Json into List[String] and then call my function or there is a direct method?
Thanks
You need implement our own io.circe.Decoder, in your case it can be converted from decoder for string.
Please, find some example code below:
import io.circe._
import io.circe.generic.auto._
object CirceExample {
class ParameterType(parameter: String) {
override def toString: String = parameter
}
class MyClass(root: ParameterType, children: List[ParameterType] = List.empty) {
override def toString: String = s"MyClass($root, $children)"
}
object MyClass {
/**
* Parsing logic from string goes here, for sake of example, it just returns empty result
*/
def parse(product: String): Either[String, MyClass] = {
Right(new MyClass(new ParameterType("example")))
}
// This is what need - just declare own decoder, so the rest of circe infrastructure can use it to parse json to your own class.
implicit val decoder: Decoder[MyClass] = Decoder[String].emap(parse)
}
case class BusinessKeys(businessKeys: List[MyClass])
def main(args: Array[String]): Unit = {
val json = "{ \"businessKeys\": [\n \"product://color?product_code\",\n \"product://?code\"\n ] }"
println(parser.parse(json).map(_.as[BusinessKeys]))
}
}
Which in my case produced next output:
Right(Right(BusinessKeys(List(MyClass(example, List()), MyClass(example, List())))))
Hope this will help you!

How to save struct to Realm, with list of another struct

i created data persistent layer in struct according to this guide, but i also need to create some realm object with struct and add it to another Realm object in struct, like array. I mean something like that:
public struct Publisher {
public let identifier: Int
public let name: String
}
public struct Character {
public let identifier: Int
public let name: String
public let realName: String
var publisherArray: [Publisher]
}
final class PublisherObject: Object {
dynamic var identifier = 0
dynamic var name = ""
override static func primaryKey() -> String? {
return "identifier"
}
}
final class CharacterObject: Object {
dynamic var identifier = 0
dynamic var name = ""
dynamic var realName = ""
var publisherArray: List<PublisherObject>?
override static func primaryKey() -> String? {
return "identifier"
}
}
In above guide, author added to struct only one another struct, not array.
I got to this point:
extension Character: Persistable {
public init(managedObject: CharacterObject) {
identifier = managedObject.identifier
name = managedObject.name
realName = managedObject.realName
publisherArray = managedObject.publisherArray
.compactMap(Publisher.init(managedObject:))
}
}
but i don't know, what i must type here:
public func managedObject() -> CharacterObject {
let character = CharacterObject()
character.identifier = identifier
character.name = name
character.realName = realName
// here must be something like that, but for array
// character.publisherArray = publisherArray.managedObject()
return character
}
Thanks all of you for help :-)
Instead of making duplicate classes for your every struct, just use Unrealm which will take care everything for you. Just make your structs/enums conform from Realmable protocol. You can save not only an array of Structs but also dictionaries, optional types, atc..
First look:
Here is an example project of how to implement the abstraction layer for the persistency:
link to github
I finally solved my problem :-)
public func managedObject() -> CharacterObject {
let character = CharacterObject()
character.identifier = identifier
character.name = name
character.realName = realName
publisherArray.forEach({ publisher in
character.publisherArray.append(publisher.managedObject())
})
return character
}

Swift Realm [[String]] object

I'm new to Realm and have been through the documentation a few times. I need to persist a [[String]] and have not found a way to do it yet
var tableViewArray = [[String]]()
I see the documentation pointing to Lists but I've been unsuccessful at implementing them. I'm showing my whole process here but just need help persisting my var tableViewArray = [[String]]()in Realm
This is my class
class TableViewArrays {
var tableViewArray = [[String]]() // populates the Main Tableview
/// add picker selection to tableview array
func appendTableViewArray(title: String, detail: String, icon: String ) {
var newRow = [String]()
newRow.append(title)
newRow.append(detail)
newRow.append(icon)
tableViewArray.append(newRow)
}
In the View Controller I instantiate the object
var tableViewArrays = TableViewArrays()
Then call the class function to populate the object
var tableViewArrays.appendTableViewArray(title: String, detail: String, icon: String )
Thank you for taking a look
I would make two Realm objects to be persisted, then nest them. Here's an example:
class RealmString: Object {
dynamic var value = ""
}
class RealmStringArray: Object {
let strings = List<RealmString>()
}
class TableViewArray{
let stringArrays = List<RealmStringArray>()
}
I can't say much about the efficiency of this method, but I suppose it should work for your purpose. Also, if you have a large amount of data, it may become a pain to persist each individual string, then string collection, the string collection collection.
create the classes
class TableViewRow: Object {
dynamic var icon = ""
dynamic var title = ""
dynamic var detail = ""
override var description: String {
return "TableViewRow {\(icon), \(title), \(detail)}" }
}
class EventTableView: Object {
let rows = List<TableViewRow>()
}
then instantiate the objects and append
let defaultTableview = EventTableView()
let rowOne = TableViewRow()
rowOne.icon = "man icon" ; rowOne.title = "War Hans D.O.P." ; rowOne.detail = "Camera Order Nike 2/11/17"
defaultTableview.rows.append(objectsIn: [rowOne])

How to save an array to a Realm Object

I am new to using Realm. Is there an easy way to save an array to a realm object? I am receiving my data from a JSON REST call:
class SomeClass: RLMObject {
dynamic var id = 0
dynamic var name = ""
dynamic var array: NSArray
func checkForUpdates() {
// Download JSON data here... The results have an array inside of them.
SomeClass.createOrUpdateInDefaultRealmWithObject(SomeNSDictionary)
}
override class func primaryKey() -> String! {
return "id"
}
}
Is it possible to save the array in the JSON results in Realm?
Thanks.
Realm has a special RLMArray type, which allows storing a collection of RLMObject's tied to a parent RLMObject. For example, say you had the following JSON:
{
"name": "John Doe",
"aliases": [
{"alias": "John"},
{"alias": "JD"}
]
}
You could model this with the following classes:
class Alias: RLMObject {
dynamic var alias = ""
}
class Person: RLMObject {
dynamic var name = ""
dynamic var aliases = RLMArray(objectClassName: "Alias")
}
So you could simply create a Person object with the following API call:
Person.createInRealm(realm, withObject: jsonObject)
You can learn more about how RLMArrays work from Realm's reference documentation: http://realm.io/docs/cocoa/0.80.0/api/Classes/RLMArray.html

Resources