Unable to parse plist in Cocos2dx 3.0 - cocos2d-x

I want to parse this plist structure...Please help
What I am using right now is
mainDictionary = __Dictionary::createWithContentsOfFile(plistPath.c_str());
__Dictionary *exit = (__Dictionary*)__Dictionary::createWithDictionary(
(__Dictionary*)mainDictionary->objectForKey(std::string("otherButton")));
But there are keys missing exit dictioanry...

In 3.0+ version the data structure like CCDictionary CCArray are deprecated. You have to use ValueMap or ValueVector etc
You can find the data structure under the folder ValueVector > CCValue.h
Here's the code for reading this plist:
cocos2d::ValueMap gameData;
gameData = FileUtils::getInstance()->getValueMapFromFile("data.plist");
In case you want to read the values:
//1
std::string backgroundValue = gameData.at("background");
//2
ValueMap otherButtonsMap = gameData.at("otherButton").asValueMap();
std::string tagValue = otherButtonsMap.at("Tag");
//3
ValueVector buttonsVector = gameData.at("Buttons").asValueVector();
ValueMap item0 = buttonsVector.at(0).asValueMap();
Where the gameData is ValueMap (or in other words Dictionary or Map or HashMap)
Edit:
The answer by "Wez Sie Tato" is correct but in your case you should read the plist in ValueMap instead of ValueVector, because your plist is actually the Dictionary(ValueMap) and not the Array(ValueVector).

Try use ValueMap and FileUtils to load PList file. The way you try to load dictionary is from cocos2d-x v2.x. In cocos2d-x you should do something like this:
ValueMap mainDictionary = FileUtils::getInstance()->getValueMapFromFile(plistPath.c_str());
ValueMap exit = mainDictionary["otherButton"].asValueMap();

There is simply no key named "ExitButton" in the root of the plist (and thus in mainDictionary).
The mainDictionary keys will be "background", "otherButton" and "Buttons", each returning another Dictionary or Array instance.
If the "ExitButton" key is somewhere in the Buttons array, you have to enumerate the Buttons array and find the "ExitButton" key in one of the array items.

Related

lua dkjson get value from json array

local json = require ("dkjson")
local obj = {"dogs":[{"photo":"http://example.com/1.jpg","price":20}]}
obj_t = json.decode(obj)
I'm use construction: obj_t.dogs.photo and this return nil
This is not a valid Lua code, but if we fix the string (local obj = [==[{"dogs":[{"photo":"http://example.com/1.jpg","price":20}]}]==]) then it looks like the problem is that you have a map with an array that has a map in it, so you're missing accessing the array element. You need to use something like obj_t.dogs[1].photo.

LINQ on JArray always returning null

I'm trying to parse some Json in Xamarin.Forms
I'm pretty new to Xamarin, though not to .net
Here's my simple dimple code
var htc = new HttpClient();
var rsp = await htc.GetStringAsync("myurl.com");
JArray lists = JArray.Parse(rsp);
var c = lists.Count();
var l = lists.ToList();
var w=lists.Where(x => true);
Even though c returns the correct count of items in the list, l & w are both null
How come? and how do I fix it?
Thanks!
PS. What I'm really trying to do is bind a ListView to a JArray, but it seems impossible directly,(Text={Binding MyPropertyName} crashes the app). so I'm trying to run a Select on the JArray to convert to a KeyValuePair. If you have any ideas to bind directly, that would be best!
UPDATE
The issue seems even odder
I tried this
var kvlist = new List<KeyValuePair<string, string>>();
foreach (JObject ll in lists)
{
kvlist.Add(new KeyValuePair<string, string>(ll["Name"].ToString(), ll["Name"].ToString()));
}
Here at least the iteration works nicely, but the kvlist is null the entire time. Trying to evaluate the kvlist variable, I get:
Unable to cast object of type 'System.RuntimeType' to type
'Mono.Debugger.Soft.TypeMirror'.
What can the matter be?
Thanks again!
You should not directly call .ToList on object type of JArray rather you should Select List of type you need. For ex.
var l = lists.Select(c => new MyList
{
Item1 = c.Value<int>("ItemName1"),
Item2 = c.Value<string>("ItemName2")
}).ToList(); //Replce MyList with your class name
On the second case where w is null, after getting list l you need to specify attribute, based of what you are using where clause. For ex.
var w=l.Where(x =>x.isAdmin==true); //l is list you selected above
Hope it help you.
Solution:
You can use code below to convert a JArray to a list<T>:
List<T> t =lists.ToObject<List<T>>();
Refer: https://www.newtonsoft.com/json/help/html/ToObjectType.htm
You could also use JsonConvert.DeserializeObject to convert it directly into the desired type. You have to define a jsonModel class with the same structure of your json fisrtly.
List<jsonModel> modelList = JsonConvert.DeserializeObject<List<jsonModel>>(jsonStr);
Refer :https://www.newtonsoft.com/json/help/html/SerializingCollections.htm
The documentation seems to indicate that JArray has properties for .Count, but no overload method because it does not implement IEnumerable, however as alluded to in the comments, it does implement the JToken type (which JArray is a collection of) and implements IEnumerable.
See the following documentation for JToken: https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JToken.htm
and JArray respectively:
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JArray.htm
The preferred mechanism is to create a strong type and then run .ToObject();
You can access JArray.ChildrenTokens which may help

Parsing JSON Data from URL with Android Studio

I'm trying to parse JSON data from URL and show the data in my app.
JSON Example (After accessing specific URL):
[{"placeID":"1","placeName":"Test Place","city":"New York","type":"Rest"..
How I can read this data and show a list of the places recieved from the API?
I've been trying ALL of the guides over the internet for parsing JSON data from URL with Android Studio and without. As a total beginner with Android developement, I couldn't make one working exmaple with json even when the author shared the final example for download. I hope you can help me in noob-friendly way and step by step or refer me to the right places.
Thank you!
I believe Android uses org.json as the JSON library, in which case something like this works to retrieve information about each place (assuming data is a valid JSON string)
try {
String data = "\"[{\"placeID\":\"1\",\"placeName\":\"Test Place\",\"city\":\"New York\",\"type\":\"Rest\"..";
JSONArray places = new JSONArray(data);
for (int i = 0; i < places.length(); i++)
JSONObject place = (JSONObject) places.get(i);
int id = place.getInt("id");
String name = place.getString("placeName");
String city = place.getString("city");
// etc...
// Do what you wish with the id, name, city and other variables.
// It loops through here for each item in the JSON variable.
}
} catch (JSONException e) {
e.printStackTrace();
}
This goes through each place in the JSON array and grabs some of the variables from it. It would probably be smart to create a data class and call it something like Place. You could then pass in the data with a constructor: new Place(id, name, city); (see this constructor for example: https://stackoverflow.com/a/22419370/5236779).

Generate a JSON object form a the value of another JSON in WP8

I am working on a WP8 app. In this I need to connect to web services whose results will be some JSON. I was trying to extract some data from the result that the web service provide. I was able to extract from the initial JSON response. But I need to get some data from the value of one such key . SO I tried to generate another Json object from it. But I m stuck. please help.Please find my example code below(I am using Newtonsoft.JSon).
private void messages_buttons_Click(object sender, RoutedEventArgs e)
{
var str = "{'status': '0', 'result': '%7B%22campaign_id%22%3A%221%22%2C%22tfn%22%3A%2218773374136%22%2C%22campaign_code%22%3A%22PJC%22%2C%22ad_id%22%3A%221%22%2C%22qr_url%22%3A%22http%3A%5C%2F%5C%2F1d1.us%5C%2FPJC%5C%2F%22%2C%22campaign_name%22%3A%22PJ+Test+Campaign%22%2C%22is_active%22%3A%221%22%2C%22expire_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22start_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22alias%22%3A%22%22%2C%22icon_image_url%22%3A%22products%5C%2Fpjc%5C%2Fpjc3.jpg%22%2C%22fb_page_url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com%5C%2FJackLaLannePowerJuicerssfb%22%2C%22video_url%22%3A%22http%3A%5C%2F%5C%2Fyoutube.com%5C%2Fembed%5C%2FyZPedpRA9r0%3Fshowinfo%3D0%26autoplay%3D1%26loop%3D1%26playlist%3DyZPedpRA9r0%22%2C%22url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com'}";
JObject ne = JObject.Parse(str);
var x= (ne.GetValue("result")).ToString();
var z = x.Replace("%", "");
JObject newest = JObject.Parse(z);
var y = newest.GetValue("campaign_id");
MessageBox.Show(y.ToString());
}
I get an exception at "JObject newest = JObject.Parse(z);" with the message
Unexpected character encountered while parsing number: m. Path '', line 1, position 6.
Am I doing it entirely wrong?
On a general note: can I convert a value from one Json to a another JSOn Itself? i.e if the value of one json key is a string with some key value pairs, can i make a json object on that string?
You can't actually just remove the % chars to get a valid value. You need to decode the string.
If you use this:
HttpUtility.UrlDecode(x);
You'll find your "result" is actually invalid JSON:
{"campaign_id":"1","tfn":"18773374136","campaign_code":"PJC","ad_id":"1","qr_url":"http://1d1.us/PJC/","campaign_name":"PJ
Test Campaign","is_active":"1","expire_on":"2021-05-05
00:00:00","start_on":"2021-05-05
00:00:00","alias":"","icon_image_url":"products/pjc/pjc3.jpg","fb_page_url":"https://www.facebook.com/JackLaLannePowerJuicerssfb","video_url":"http://youtube.com/embed/yZPedpRA9r0?showinfo=0&autoplay=1&loop=1&playlist=yZPedpRA9r0","url":"https://www.facebook.com
So hacking the value to make it valid JSON might work for you, by adding the missing "} at the end should turn your value in to valid JSON and allow you to parse it.
JObject newest = JObject.Parse(x + "\"}");
var y = newest.GetValue("campaign_id");
It doesn't appear that z is a valid json object at this point. It is only the value of result. Try something like JObject.Parse("'result':" + z);

Replacing string in html dynamically in Android

I am using "loadDataWithBaseUrl(...)" to load a html file, stored in assets, to Webview. that contains a string "Loading..." and a rotating GIF. String "Loading..." is hard coded, and it'll not be localized. How to replace that string dynamically, so that it can be localized?
Please help me to resolve this.
There are various solutions I could think of :
Load a different asset file according to the current language (get the current language using Locale.getDefault()), This way you can translate your HTML files independently.
Use place holders in your HTML file (for instance #loading_message#), then load the asset file in a String, replace all the occurences of the placeholder by the appropriate localised message (String.replaceAll("#loading_message#", getText(R.string.loading_message).toString())), finally load the processed HTML into the WebView using the loadData(String data, String mimeType, String encoding) function.
To load the asset file, you can do something like that:
File f = new File("file:///android_asset/my_file.html");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String eachLine = br.readLine();
while(eachLine != null) {
sb.append(eachLine);
sb.append("\n");
eachLine = br.readLine();
}
// sb.toString is your HTML file as a String
I had a similar problem when using the WebView to show help text that should be translated.
My solution was to add multiple translated HTML files in assets and loading them with:
webView.loadUrl("file:///android_asset/" + getResources().getString(R.string.help_file));
For more details go to: Language specific HTML Help in Android
String str = "Loading ..."
String newStr = str.substring("Loading ".length());
newStr = context.getResourceById(R.string.loading) + newStr;
I hope the code is sufficiently clear to understand the idea: extract the string without "Loading " and concatenate it with the localized version of "Loading" string