How do I get data from this json field? - json

How are you doing?
I'm trying to get data from a json to show on a screen that should be like the image below. I'm able to get most of the data, except for one field coded as String which consists of the image and a description like this one:
"lessonText": "{\"ops\":[{\"insert\":{\"image\":\"data:image/jpeg;base64,(IMAGE CODE HERE)=\"}},{\"attributes\":{\"color\":\"#444444\"},\"insert\":\"(LESSON TEXT HERE)\"},{\"insert\":\"\\n\"}]}",
How do I extract data from here? I have tried to convert this to a Map but it is not working.
Thanks for the help!

Something in line with this should give you the image
// json string containing the base64 image string
String jsonString = "{\"ops\":[{\"insert\":{\"image\":\"data:image/png;base64,(IMAGE CODE HERE)=\"}},{\"attributes\":{\"color\":\"#444444\"},\"insert\":\"(LESSON TEXT HERE)\"},{\"insert\":\"\\n\"}]}";
// convert the string to a map structure
Map<String, dynamic> json = jsonDecode(jsonString);
// extract the image string
String imageString = json['ops'][0]['insert']['image'];
// extract the base64 string
var prefix = "data:image/png;base64,";
var imageBase64String = imageString.substring(prefix.length);
// decode the base 64 string
var bytes = base64Decode(imageBase64String);
// build the image widget from bytes
var imageWidget = Image.memory(bytes);

As I mentioned in the comments, use a combination of decoding the base64 string to bytes and then loading the image from memory. See the the relevant documentation for base64Decode and Image.memory. If you would like a full code sample just let me know and I would be happy to throw one together.
Note: you should run the base64Decode method asynchronously, as it may take some time to decode an entire image (especially on lower-end hardware).

Related

How to insert a Picture Object from Json Datasource to List & Label report

I use List & Label to generate various reports from database content. The output is handeled by a middleware service which receives the data as Json payload.
Up to now I did not manage to display images/pictures in reports such as i.e. an Itempicture on a customer quotation.
Does anyone may know, which graphic format is expected by the report designer picture object and/or which function might have to be used?
Drawing({String}) expects a path to a physical image file -> hence can not use it because the image data is available as kind of raw image text.
Any help ist highly appreciated.
It will work, if you handle this points:
the field within the JSON need to be base64 encoded - you can get it like this:
using (var memory = new MemoryStream())
{
using (var picture = new Bitmap(<YOURPIC>))
{
picture.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg);
var base64 = Convert.ToBase64String(memory.GetBuffer());
}
}
use the AutoDefineField-Event of the List & Label object and override FieldType for the matching picture field with its base64 content to LlFieldType.Drawing - e.g.:
private void LL_AutoDefineField(object sender, AutoDefineElementEventArgs e)
{
if (e.Name == "Contacts.myPic")
{
e.FieldType = LlFieldType.Drawing;
}
}

How to convert image to Base64 and include in Json as result

newBie in asp.net WebApi.
1) How to resize an image and convert it to base64 and return it to Client.
2) I am not sure about the pro and con on base64 conversion vs byteArray for image.
3) Which format is better to use in webApi
return image in byteArray or Base64 in json.
understand these are allowable dataType. So, sending image bytes is not ok.
In JSON, values must be one of the following data types:
a string
a number
an object (JSON object)
an array
a boolean
null
I need fast processing for webApi.
Your help is greatly appreciated.
Thanks
You need to use atob to base64 decode and use btoa to encode
you need to Escape datas before to encode base64
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
// Usage:
var test1 = utf8_to_b64('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
var test2 = b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
console.log(test1);
console.log(test2)
base more complet for more type of data https://developer.mozilla.org/fr/Add-ons/Code_snippets/StringView

parsing JSON on appcelerator

i have a webservice like this:
{"person":{"name account":"Jhon Doe","Image":"image/test","Adress":"New York 43","Recomendations":"40"}}
this is what i'm trying to do, when i print datos i get the whole json but when i try to print just the name or Image i don't get anything
var urll = "example.com/example";
var json;
var xhrr = Ti.Network.createHTTPClient({
onload: function() {
json = JSON.parse(this.responseText);
var datos = JSON.stringify(json);
var medicos = datos;
Ti.API.info("Json! "+datos);
}
});
xhrr.open('GET', urll);
xhrr.send();
i tried with datos[0].person, datos.person but nothing
You have to understand the difference between a string that contains a JSON representation of an object - and the object itself.
Your json variable contains the object (which is what JSON.parse(...) does - convert a text string to an object). On the object you can refer to the attributes as you discovered. You can do this in two ways:
json.person.Address
json.person['name account']
I would suggest that you try to avoid attributes with names that are not valid identifiers (as the latter of the two) as this makes it a little more difficult to use them - e.g. by not allowing the dot notation.
Your datos variable on the other hand contains the string representation of the json object (as JSON.stringify(...) does exactly that - convert an object to its string representation). This means that datos is the same as this.responseText (since you first parse it and then stringify it back).
So JSON.stringify(...) is a brilliant way to make the object "human readable" but you need the object to work with the data.
Hope this clarifies the terms a little ;-)
/John
i just find the solution:
Ti.API.info("Json! "+json.person.Recomendations);

Strange Base64 encode/decode problem

I'm using Grails 1.3.7. I have some code that uses the built-in base64Encode function and base64Decode function. It all works fine in simple test cases where I encode some binary data and then decode the resulting string and write it to a new file. In this case the files are identical.
But then I wrote a web service that took the base64 encoded data as a parameter in a POST call. Although the length of the base64 data is identical to the string I passed into the function, the contents of the base64 data are being modified. I spend DAYS debugging this and finally wrote a test controller that passed the data in base64 to post and also took the name of a local file with the correct base64 encoded data, as in:
data=AAA-base-64-data...&testFilename=/name/of/file/with/base64data
Within the test function I compared every byte in the incoming data parameter with the appropriate byte in the test file. I found that somehow every "+" character in the input data parameter had been replaced with a " " (space, ordinal ascii 32). Huh? What could have done that?
To be sure I was correct, I added a line that said:
data = data.replaceAll(' ', '+')
and sure enough the data decoded exactly right. I tried it with arbitrarily long binary files and it now works every time. But I can't figure out for the life of me what would be modifying the data parameter in the post to convert the ord(43) character to ord(32)? I know that the plus sign is one of the 2 somewhat platform dependent characters in the base64 spec, but given that I am doing the encoding and decoding on the same machine for now I am super puzzled what caused this. Sure I have a "fix" since I can make it work, but I am nervous about "fixes" that I don't understand.
The code is too big to post here, but I get the base64 encoding like so:
def inputFile = new File(inputFilename)
def rawData = inputFile.getBytes()
def encoded = rawData.encodeBase64().toString()
I then write that encoded string out to new a file so I can use it for testing later. If I load that file back in as so I get the same rawData:
def encodedFile = new File(encodedFilename)
String encoded = encodedFile.getText()
byte[] rawData = encoded.decodeBase64()
So all that is good. Now assume I take the "encoded" variable and add it to a param to a POST function like so:
String queryString = "data=$encoded"
String url = "http://localhost:8080/some_web_service"
def results = urlPost(url, queryString)
def urlPost(String urlString, String queryString) {
def url = new URL(urlString)
def connection = url.openConnection()
connection.setRequestMethod("POST")
connection.doOutput = true
def writer = new OutputStreamWriter(connection.outputStream)
writer.write(queryString)
writer.flush()
writer.close()
connection.connect()
return (connection.responseCode == 200) ? connection.content.text : "error $connection.responseCode, $connection.responseMessage"
}
on the web service side, in the controller I get the parameter like so:
String data = params?.data
println "incoming data parameter has length of ${data.size()}" //confirm right size
//unless I run the following line, the data does not decode to the same source
data = data.replaceAll(' ', '+')
//as long as I replace spaces with plus, this decodes correctly, why?
byte[] bytedata = data.decodeBase64()
Sorry for the long rant, but I'd really love to understand why I had to do the "replace space with plus sign" to get this to decode correctly. Is there some problem with the plus sign being used in a request parameter?
Whatever populates params expects the request to be a URL-encoded form (specifically, application/x-www-form-urlencoded, where "+" means space), but you didn't URL-encode it. I don't know what functions your language provides, but in pseudo code, queryString should be constructed from
concat(uri_escape("data"), "=", uri_escape(base64_encode(rawBytes)))
which simplifies to
concat("data=", uri_escape(base64_encode(rawBytes)))
The "+" characters will be replaced with "%2B".
You have to use a special base64encode which is also url-safe. The problem is that standard base64encode includes +, / and = characters which are replaced by the percent-encoded version.
http://en.wikipedia.org/wiki/Base64#URL_applications
I'm using the following code in php:
/**
* Custom base64 encoding. Replace unsafe url chars
*
* #param string $val
* #return string
*/
static function base64_url_encode($val) {
return strtr(base64_encode($val), '+/=', '-_,');
}
/**
* Custom base64 decode. Replace custom url safe values with normal
* base64 characters before decoding.
*
* #param string $val
* #return string
*/
static function base64_url_decode($val) {
return base64_decode(strtr($val, '-_,', '+/='));
}
Because it is a parameter to a POST you must URL encode the data.
See http://en.wikipedia.org/wiki/Percent-encoding
paraquote from the wikipedia link
The encoding used by default is based
on a very early version of the general
URI percent-encoding rules, with a
number of modifications such as
newline normalization and replacing
spaces with "+" instead of "%20"
another hidden pitfall everyday web developers like myself know little about

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