JSON is disregarding the backslashes on line 3. I want whatever is between double quotes from line 3 to 18 as a string.
This is my JSON code:
{
"schema":
"syntax = \"proto3\";
message SearchRequest {
float eventVersion = 1;
string producedBy = 2;
string asupSubject = 3;
int64 sysSerialNo = 4;
int64 systemId = 5;
string rawAsupPath = 6;
int64 completedTimestamp = 7;
string sourceQueue = 8;
.SearchRequest.addonattributes addOnAttributes = 9;
message addonattributes {
string asupSecureType = 1;
string sesgFlag = 2;
}
}",
"schemaType": "PROTOBUF"
}
This is the output received:
{
"error_code": 400,
"message": "Illegal unquoted character ((CTRL-CHAR, code 13)): has to be escaped using backslash to be included in string value\n at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 3, column: 27] (through reference chain: io.confluent.kafka.schemaregistry.client.rest.entities.requests.RegisterSchemaRequest[\"schema\"])"
}
Its actually the linebreaks that are breaking it. Try this:
{
"schema":
"syntax = \"proto3\";\n message SearchRequest {\n float eventVersion = 1;\n string producedBy = 2;\n string asupSubject = 3;\n int64 sysSerialNo = 4;\n int64 systemId = 5;\n string rawAsupPath = 6;\n int64 completedTimestamp = 7;\n string sourceQueue = 8;\n .SearchRequest.addonattributes addOnAttributes = 9;\n message addonattributes {\n string asupSecureType = 1;\n string sesgFlag = 2;\n }\n }",
"schemaType": "PROTOBUF"
}
Note: This works for you're initial text here, if you have other special characters in the future they will need escaped accordingly.
Additional Note: As pointed out in the comment, storing child JSON not ideal and I suspect it will make the solution difficult to maintain.
Related
I am getting float value in string format from JSON like below
JSON:
{
"result": {
"conversion_factor": {
"conv_factor": "0.820000"
}
"search_result": [
{
"service_details": [
{
"standard_rate_in_usd": "10.00",
now i need to multiply conv_factor * standard_rate_in_usd
code: with this code only first value coming correct remaining showing wrong why?
let indexData = searchResult?.result?.search_result?[indexPath.row]
if let servDetls = indexData?.service_details{
for oneSerdet in servDetls{
var stringPrice: String?
if var priceVal = Float(oneSerdet.standard_rate_in_usd!), var convVal = Float((searchResult?.result?.conversion_factor?.conv_factor)!) {
stringPrice = String(priceVal * convVal)
}
else{
stringPrice = ""
}
cell.priceLbl.text = "£ \(stringPrice ?? "") \(currData)"
}
}
You need to convert to floats:
let convResult = Float(oneSerdet.standard_rate_in_usd) *
Float(searchResult?.result?.conversion_factor?.conv_factor)
Try this, hope this will resolves your issue
if let conv_factor = oneSerdet.conv_factor,
let factor = Double(conv_factor),
let standard_rate_in_usd = oneSerdet.standard_rate_in_usd,
let usd = Double(standard_rate_in_usd) {
print(factor*usd)
cell.priceLbl.text = "\(factor*usd)"
}else{
cell.priceLbl.text = ""
print("Unreachable")
}
You have multiple problems:
Your construct searchResult?.result?.conversion_factor?.conv_factor evaluates to an Optional String: String?.
You can't multiply strings. Strings are not numeric. You need to convert your string to a Double. But the Double initializer that takes a string also returns an Optional (since "Apple", for example, can't be converted to a Double.
Here is some sample code that will take 2 Optional Strings, try to convert them to Doubles, and multiples them.
let xString: String? = "123.456"
let yString: String? = "2.0"
let x = xString.map { Double($0) ?? 0 } ?? 0.0
let y = yString.map { Double($0) ?? 0 } ?? 0.0
let result: Double = x * y
print(result)
That outputs
246.912
I have a string that looks like following:
{\n \"account_no\" = \"5675672343244\";\n \"account_kind\" = {\n \".tag\" = test,\n };\n country = US;\n disabled = 0;\n email = \"test#gmail.com\";\n \"email_verified\" = 1;\n \"is_paired\" = 0;\n };\n}"
It is similar to NSDictionary when it is printed as description to the console. Especially
some strings are in quotes, some are not. See country = US;\n
they use k-v notation with =. E.g. key = value
they use delimiter ;
Unfortunately I do not have the original object that created the string. I have only the string itself.
My goal is to transform it to a valid JSON string representation, or alternatively back to a NSDictionary. Should be done in Swift 5. I failed so far in doing so, does anyone has sample code that would help?
The description of an NSDictionary produces an “Old-Style ASCII Property List”, and PropertyListSerialization can be used to convert that back to an object.
Note that the format is ambiguous. As an example, 1234 can be both a number or a string consisting of decimal digits only. So there is no guarantee to get the exact result back.
Example:
let desc = "{\n \"account_no\" = \"5675672343244\";\n \"account_kind\" = {\n \".tag\" = test;\n };\n country = US;\n disabled = 0;\n email = \"test#gmail.com\";\n \"email_verified\" = 1;\n \"is_paired\" = 0;\n}"
do {
let data = Data(desc.utf8)
if let dict = try PropertyListSerialization.propertyList(from: data, format: nil) as? NSDictionary {
let json = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
print(String(data: json, encoding: .utf8)!)
} else {
print("not a dictionary")
}
} catch {
print("not a valid property list:", error)
}
Output:
{
"country" : "US",
"email_verified" : "1",
"is_paired" : "0",
"account_no" : "5675672343244",
"email" : "test#gmail.com",
"disabled" : "0",
"account_kind" : {
".tag" : "test"
}
}
(I had to “fix” the description string to make it a valid property list: "test" was followed by a comma instead of a semicolon, and there was an unbalanced } at the end of the string.)
In flutter(dart), it is easy to deserialize Json and get a token from it, but when I try to serialize it again, the quotation marks around the keys and values with disappear.
String myJSON = '{"name":{"first":"foo","last":"bar"}, "age":31, "city":"New York"}';
var json = JSON.jsonDecode(myJSON); //_InternalLinkedHashMap
var nameJson = json['name']; //_InternalLinkedHashMap
String nameString = nameJson.toString();
Although the nameJson have all the double quotations, the nameString is
{first: foo, last: bar}
(true answer is {"first": "foo", "last": "bar"})
how to preserve Dart to remove the "s?
When encoding the object back into JSON, you're using .toString(), which does not convert an object to valid JSON. Using jsonEncode fixes the issue.
import 'dart:convert';
void main() {
String myJSON = '{"name":{"first":"foo","last":"bar"}, "age":31, "city":"New York"}';
var json = jsonDecode(myJSON);
var nameJson = json['name'];
String nameString = jsonEncode(nameJson); // jsonEncode != .toString()
print(nameString); // outputs {"first":"foo","last":"bar"}
}
I have this line of code, and I want to extract the "title" key:
var title = jParams["title"] as! String
However it wont let me compile, and if I get this error message in red:
Cannot subscript a value of a type AnyObject with an index of type String
When show the contents of jParams in the log with println(jParams) I get the following content:
INCOMING LIST PARAMETERS (jParameters)
Optional({
title = "Example List";
values = (
{
id = 1;
name = "Line 1";
},
{
id = 2;
name = "Line 2";
},
{
id = 3;
name = "Line 3";
}
);
})
I am new to Swift so I am not familiar with the details of handling JSON to deal with these type of problems. What could be wrong?
//jParams comes from a JSON server response
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
if data != nil {
var jdata = JSON(data: data!)
var jParams=jdata["responseData"]["extraData"]["params"]
In your edit it looks like you're using SwiftyJSON.
If that is indeed the case, you can help the compiler to know what's in the dictionary by using SwiftyJSON's dictionaryValue property:
let jParams = jdata["responseData"]["extraData"]["params"].dictionaryValue
Then you should be able to access your values without downcasting:
let title = jParams["title"]
because SwiftyJSON will have inferred the right type for the values.
I am trying to parse some JSON objects which is made just of (string,string) pairs. The file I am parsing contains this. I want ot emulate resjson behaviour.
{
"first_key": "first_value",
"unicode": "\u0040 #"
}
What I do is
string path = #"d:\resjson\example.resjson";
string jsonText = File.ReadAllText(path);
IDictionary<string, string> dict;
try
{
dict = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonText);
}
catch(Exception ex)
{
// log or something
}
When I obtain the dict object, the
foreach (var pair in _dict)
{
string key = pair.Key;
string value = pair.Value;
Console.WriteLine("Key = '{0}', Value = '{1}'", key, value);
}
This inputs for me :
"Key = 'first_key', Value = 'first_value'"
"Key = 'unicode', Value = '# #'"
Once Newtonsoft.Json deserializes the object, I lose the "\u0040" string and I have no way of knowing how the original file looked like. Is there a way to preserve character escaping ?
Well, one simple idea would be to escape all the backslashes in the original text before passing it to the parser:
dict = JsonConvert.DeserializeObject<IDictionary<string, string>>(
jsonText.Replace(#"\", #"\\"));
Using Newtonsoft.Json, you can actually do:
var settings = new JsonSerializerSettings()
{
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
var json = JsonConvert.SerializeObject([obj or JToken], settings);
It won't show the original string as that is lost when deserializing, but it will encode all non ascii characters as \uXXXX