I Have a dictionary data structure and i want to write it to XML like this
<root>
<key>House1</key>
<value>somevalue</value>
<key>House2</key>
<value>somevalue</value>
</root>
and i also want to get back data in my dictionary so far i have done this XmlTextWriter
textWriter = new XmlTextWriter("D:\\config.xml", null);
textWriter.WriteStartDocument();
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("house", "langlat");
dict.Add("house2", "langlat");
XElement el = new XElement("root", dict.Select(kv => new XElement("key", kv.Key, new XElement("value", kv.Value))));
This is to write data to XML, but when I try to read values it gives me whole things like this Houselanglat. I want house as a key and langlat should be it's value .
Related
Imagine you have the following json
{
"list": [
["xa", "yc", "ze"],
["xb", "yd", "zf"]
]
}
how do we convert this to a List<List<String>> with json.decode() in dart?
I'm going to make the assumption that this is a string before you pass it to jsonDecode, which will return a Map<String, dynamic>.
// The original string
String jsonString = "{\"list\": [[\"xa\", \"yc\", \"ze\"], [\"xb\", \"yd\", \"zf\"]]}";
// The parsed map
Map<String, dynamic> json = jsonDecode(jsonString);
Now, it seems like you don't care about the containing Map.
Technically, those things that look like Lists are actually Maps at this point, so those type assertions would fail.
List<List<String>> output = json["list"].map((value) => value.toList()).toList();
That's the most straightforward method I can think of right now.
I am able to retrieve JSON from a service using RESTAssured.
I would like to use the JSONPath capability to extract JSON and then compare it using JSONAssert.
Here's my example:
#Test
public void doAPITestExample() throws JSONException {
// retrieve JSON from service
Response response = RestAssured.given().get("http://localhost:8081/mockservice");
response.then().assertThat().statusCode(200);
String body = response.getBody().asString();
System.out.println("Body:" + body);
/*
{"datetime": "2018-06-21 17:48:07.488384", "data": [{"foo": "bar"}, {"test": "this is test data"}]}
*/
// able to compare entire body with JSONAssert, strict=false
Object data = response.then().extract().path("data");
System.out.println("Response data:");
System.out.println(data.getClass()); // class java.util.ArrayList
System.out.println(data.toString());
// JSONAssert data with strict=false
String expectedJSON = "{\"data\":[{\"foo\": \"bar\"}, {\"test\": \"this is test data\"}]}";
JSONAssert.assertEquals(expectedJSON, response.getBody().asString(), false);
// How do I extract JSON with JSONPath, use JSONAssert together?
}
Approach 1 - using JSONPath to get JSONObject
How do I get JSONPath to return a JSONObject that can be used by JSONAssert?
In the code example:
Object data = response.then().extract().path("data");
This returns a java.util.ArrayList. How can this be used with JSONAssert to compare to expected JSON?
Approach 2 - parse extracted data with JSONParser
If I do data.toString(), this returns a string that cannot be parsed due to lack of quote handling for string values with spaces strings:
String dataString = response.then().extract().path("data").toString();
JSONArray dataArray = (JSONArray) JSONParser.parseJSON(dataString);
Result:
org.json.JSONException: Unterminated object at character 24 of [{foo=bar}, {test=this is test data}]
Approach 3 - Using JSON schema validation
Is is possible to extract just the data property from the JSON and run that against JSON Schema on just that part?
Note: the entire JSON that is returned is quite large. I just want to validate the data property from it.
What would an example of doing a JSON schema validation look for just the data property from the JSON?
Thanks;
You can use the method jsonPath in your response object.
Example:
// this will return bar as per your example response.
String foo = response.jsonPath ().getString ("data[0].foo");
For more info about JSon path check here.
I have a dictionary of key-value pairs that I am trying to save to core data.
let children = userSnap.children.allObjects as! [DataSnapshot]
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let thisUser = ThisUser(context: context)
var data = [String: String]()
for child in children {
data[child.key] = child.value as? String
}
data["uid"] = currentUser!.uid
The child.key string matches the attribute in CoreData and I want to put child.value as? String in as the value for each CoreData attribute.
Is there a way I can do this without having to create a line of code for each attribute ... ex) thisUser.uid = data["uid]
Here is my data model:
You should be able to do this via Core Data introspection. You'd do something like:
Get the NSEntityDescription as thisUser.entity.
Get a list of the properties in the entity, by calling attributesByName on the entity description to get a dictionary of [String: NSAttributeDescription].
The keys for that dictionary are the names of your Core Data properties. Get values from your dictionary with that key. Assign values to your managed object with key-value coding, i.e. setValue(_:, forKey:).
If necessary you can also use the results of attributesByName to find out the type of the property. Use the attributeType property of NSAttributeDescription.
Basically, find out what attributes your Core Data object has, get their names, and then run through those names to copy data from one place to another.
TempData["Amalgamation"] = SearchList;
I am using this code already in this TempData a record is there now i want to append new data which was stored in "SearchList". How can i do that?
Assuming SearchList is a List<T>
var searchList = (List<SomeType>)TempData["Amalgamation"];
searchList.Add(...);
Is there a cleaner way to get the JSON representation of a Javascript object than with the following kludge?
System.out.println(((ScriptableObject) scope).callMethod(
cx, (Scriptable) scope.get("JSON", scope),
"stringify", new Object[]{jsObject}));
Where jsObject is the ScriptableObject I want to stringify.
Note that Hannes has now addressed this in Rhino. So the usage simplifies to this:
import org.mozilla.javascript.NativeJSON;
// ...
Object json = NativeJSON.stringify(cx, scope, jsObject, null, null);
The org.mozilla.javascript.NativeJSON class should be public in the Rhino 1.7R4 release.
I was able to get this working within an Apache Ant target using the NativeJSON class.
importPackage(org.mozilla.javascript);
var context = Context.enter();
var json = '{}';
// The call to parse required a reviver function that should return the
// state of a key/value pair.
var reviver = function(key, value) { return value; };
var scope = context.initStandardObjects();
var object = NativeJSON.parse(context, scope, json, reviver);
// The call to stringify does not require the replacer or space parameters.
// The replacer is a function that takes a key/value pair and returns the
// new value or an array of keys from the input JSON to stringify. The space
// parameter is the indentation characters or length.
json = NativeJSON.stringify(context, scope, config, null, 4);
http://mozilla.github.io/rhino/javadoc/org/mozilla/javascript/NativeJSON.html
https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/NativeJSON.java