Nesting arrays in Realm with Swift - json

I have read several examples on SO on how to store arrays of data to Realm. Still, I am not finding a particularly clear example.
In short, I have a (simplified) JSON as below which I would like to store in Realm. How can I add an array of ingredients to Realm, so that it is contained within an array of menuItems?
{
"menuItems": [
{
"name": "name 1",
"ingredients": ["ingredient 1", "ingredient 2"]
},
{
"name": "name 2",
"ingredients": ["ingredient 1", "ingredient 2", "ingredient 3"
]
}
]
}
I have my realm models set up as such:
class MenuItemsRealm: Object {
#objc dynamic var name: String = ""
var ingredients = List<IngredientItemsRealm>()
}
class IngredientItemsRealm: Object {
#objc dynamic var ingredientItem: String = ""
}

In your JSON, you're stating that a menuItem object has a property/variable called ingredients and it contains an array of String. What you probably want to do is create a array of Objects that contains the specific ingredientItem property/variable.
To exemplify your JSON would be something like this:
{
"menuItems": [
{
"name": "name 1",
"ingredients": [
{
"ingredientItem": "item name"
}
]
}
]
}

Related

How do I add names to objects in JSON using PowerShell?

I have the following situation below. I'd like to add a name to each item in the array.
First item needs to have a name instead of being an anonymous object. How do I do this?
Items need to have an name derived from the Technical Name, so 988 instead of N988AB1.
Structure of array is changed to an object in the result.
Current situation:
{
"Category": [{
"TechnicalName": "N988AB1",
"Name": "House"
},
{
"TechnicalName": "H181AG3",
"Name": "Apartment"
},
{
"TechnicalName": "X123XY5",
"Name": "Villa"
}
]
}
Desired situation:
{
"Data": {
"988": {
"TechnicalName": "N988AB1",
"Name": "House"
},
"181": {
"TechnicalName": "H181AG3",
"Name": "Apartment"
},
"0123": {
"TechnicalName": "X0123XY5",
"Name": "Villa"
}
}
}
One way of tackling this: (You can copy and paste the full contents of the code box to try it out. I've commented what various steps are doing)
$ExistingJson = #"
{
"Category": [{
"TechnicalName": "N988AB1",
"Name": "House"
},
{
"TechnicalName": "H181AG3",
"Name": "Apartment"
},
{
"TechnicalName": "X123XY5",
"Name": "Villa"
}
]
}
"#
# Convert the json string to an object we can manipulate.
$ExistingObj = $ExistingJson | ConvertFrom-Json
# Create an empty hashtable for the new items we are creating.
$HT = #{}
foreach ($Category in $ExistingObj.Category) {
# Match any digits, grouped as "name", after any character [A-Za-z] which are followed by [A-Za-z] - this is pretty basic and may need to be changed if your TechnicalName string changes, or you want different information from it.
[System.Void]($Category.TechnicalName -match "(?<=[A-Za-z])(?<name>\d+)(?=[A-Za-z])")
$NewItem = [PSCustomObject]#{
TechnicalName = $Category.TechnicalName
Name = $Category.Name
}
# Add a new entry to the hashtable with the discovered digits by it's group name "name" and the object created above with the existing information as it's value.
$HT.Add($Matches["name"], $NewItem)
}
# Create a new object with a Data property with the value as the hashtable.
$NewObj = [PSCustomObject]#{
Data = $HT
}
# Convert it back to Json
$NewObj | ConvertTo-Json
Results in:
{
"Data": {
"988": {
"TechnicalName": "N988AB1",
"Name": "House"
},
"181": {
"TechnicalName": "H181AG3",
"Name": "Apartment"
},
"123": {
"TechnicalName": "X123XY5",
"Name": "Villa"
}
}
}

parsing json object with number as its key fields?

I'm trying to parse json into kotlin objects but the problem is that its key fields are numbers any idea how can parse them , I've tried serialized name but still facing problem.
The json response looks like this :
{
"Id": [{
"1": {
"name": "name1",
"class": "11a"
}
},
{
"2": {
"name": "name2",
"class": "11b"
}
}
]
}
I'm using gson and the main thing i'm trying to do is to store this number fields as some other string objects.
You can parse them into a list of maps, then "map" those to your data classes instead:
val input = """{
"Id": [{
"1": {
"name": "name1",
"class": "11a"
}
},
{
"2": {
"name": "name2",
"class": "11b"
}
}
]
}"""
val gson = Gson()
val parsed: Map<String, List<Map<String, Any>>> =
gson.fromJson(input, (object : TypeToken<Map<String, List<Map<String, Any>>>>(){}).type)
println(parsed["Id"]?.get(0)?.get("1")) // {name=name1, class=11a}
It will have some nasty generic signature, though.
If you're working with Kotlin, take a look at Klaxon, it will improve your experience.

parsing nested json data - access directly to a member

I have json data like
data = {
"id":1,
"name":"abc",
"address": {
"items":[
"streetName":"cde",
"streetId":"SID"
]
}
}
How can i access directly to the streetName Value ?
Your json is actually invalid. If you have control over the json generation, first change it to this:
data = {
"id": 1,
"name": "abc",
"address": {
"items": [{
"streetName": "cde",
"streetId": "SID"
}]
}
}
Notice the additional braces around streetName and streetId. Then, to access streetName, do this:
var streetName = data.address.items[0].streetName;

Get a object from json based on a specific value

I have a json string. I need to get a specific object based on an id value. Suppose I entered 2, then I want {"id":"2","name":"def"} as the result. I want this to be done in java class.
[
{"id":"1",
"name":"abc"},
{"id":"2",
"name":"def"}
]
Put the Objects in the Array for better manipulation..!!!
JSONObject data = new JSONObject(YOUR_JSON);
JSONArray data_Values=data.getJSONArray(values);
int n=2;// Entered ID
for(int i=0;i<=data_Values.length();i++)
{
if(n==data_Values.getInt("id"))
{
id=data_Values.getInt("id");
name=data_Values.getString("name");
}
}
JSON Data
{
"Values": [
{
"id": "1",
"name": "ABC"
},
{
"id": "2",
"name": "EFG"
},
{
"id": "3",
"name": "HIJ"
}
]
}

Unable to construct java object from json

Can any body tell me Java class structure equivalent to below json:
{
"status": "OK",
"data":
{
"group_id":2758,
"0":
{
"id": "2758-1",
"customid": "1",
"customid1": "",
"customid2": "",
"mobile": "9190********",
"status": "AWAITED_DLR",
},
"1":
{
"id": "2758-2",
"customid": "2",
"customid1": "",
"customid2": "",
"mobile": "9190********",
"status": "AWAITED_DLR",
}
...
}
"message": "Campaign Submitted successfully"
}
Unable to decide the structure of data object as it contains group_id and list of other object.
You can make a first class which represents your structure with :
an Int : group_id
an ArrayList : data, that contains objects of type Item
Then you create the second class Item that represents the structure of "0" and "1".
If you want to keep the label "0", "1" you can make the type of data an Hashmap<String,Item> instead of ArrayList.
You could use a map:
class Data {
int group_id;
Map<Integer, InnerObject> map = new HashMap<>();
}
Data data = new Data();
data.group_id = 2758;
data.map.put(0, innerObject0);
data.map.put(1, innerObject1);