I'm trying to load a json file from a URL and parse it within Dart. So I had tried the following code as suggested from some links when I google for it:
HttpRequest.getString("hellknight2.js").then((response)
{
var model = new JSON.parse(response);
});
However, it seems to not work anymore on Dart SDK version 0.4.3.5_r20602. What is the current best way to get a Json file mapped to an object in Dart?
Simply use json of the dart:convert package. Here is an example :
import 'dart:convert';
main() {
final myJsonAsString = '{"a": 1, "b": "c"}';
final decoded = json.decode(myJsonAsString);
....
}
See Parsing JSON for more details.
in my case
JSON.decode
didn't work.
Instead I had to use :
import 'dart:convert' as JSON;
final json=JSON.jsonDecode(myJsonAsString);
Here is my solution :) At first, you need to import the convert package:
import 'dart:convert';
var res = json.decode(response.body);
then you can get values by key, like below:
print(res["message"]);
It depends on a lot of things.
Is the json text you get is an array or a map?
You can try with:
Map model = new parse(response);
Or
List model = new parse(response);
but you need to import JSONObject by Chris Buckett into your package
import "package:json_object/json_object.dart";
You can install it from pubspec adding this dependency
json_object
There's a new pub package for this:
Victor Savkin - Serializers.
I didn't use it but seems to me that it will suite you. Try it out
you can try this package. pub: g_json
dynamic model = JSON.parse(JsonStringFromAnywhere);
final name = model['name'].stringValue;
// OR
final name = model.name;
Related
I am unable to parse json file if values contain single quote and other characters as '()= etc
Hi I have the following Json file:
{
"config": {
"inputDFName": "testInput",
"conditions": "site_type = 'micro'"
}
}
The parser class like
case class FilterConfig(inputDFName: String,conditions: String)
I am parsing json using below function
def readDataFilter(conf:String): FilterConfig ={
val gson = new Gson()
gson.fromJson(conf,classOf[FilterConfig])
}
But return error like : com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException
but if i remove single quotes and equal to sign its working fine.
Please help here.
I see two problems here.
inputDFName in JSON is not matching with testDFName in FilterConfig class.
Your JSON structure is different from that of FilterConfig.
I tried to run the code with the above changes and its working fine.
case class FilterConfig(inputDFName: String,conditions: String)
import com.google.gson.Gson;
def readDataFiltr(conf:String): FilterConfig ={
val gson = new Gson()
gson.fromJson(conf,classOf[FilterConfig])
}
val x = readDataFiltr("{\"inputDFName\": \"testInput\", \"conditions\": \"site_type = 'micro'\"}")
println(x.inputDFName)
println(x.conditions)
Please let me know if this is not clear.
Thanks,
Vivek
I am working on a Scala app. I have a method that gives me JSON and I convert it to string using toString as follows:
def myjson(fileName:String){
val myJson = myData.getJsonData().toString
}
Here getJsonData() will give me a .json. I want to write this .json into a file and save this .json in resources section in my project. Format of the file should be ".json". Name of the file is the one which I am getting in above method. How can I do that?
One approach would be as follow
import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets
def myjson(fileName:String){
val myJson = myData.getJsonData().toString
val path = s"/user/myProject/..../resources/$fileName"
Files.write(Paths.get(path), myJson.getBytes(StandardCharsets.UTF_8))
}
I understand that fileName: String will be something like filename.json
I have a JSON file in the flutter directory, not in assets.
json_data.json:-
{
"foo" : "bar"
}
I want to read this JSON on different files.
like
myfile.dart:-
import "package:mypackage/json_data.json" as data;
import 'dart:convert';
var my_data = json.decode(data);
I am getting the error:-
The name 'data' refers to an import prefix, so it must be followed by '.'.
Try correcting the name to refer to something other than a prefix, or renaming the prefix.
What is the problem here? why can't I read JSON from local import in flutter?
You should look into loading assets in flutter. You can't simply import an arbitrary file. Importing is for source code/libraries.
You need to declare this file as an asset in your pubspec.yaml
flutter:
assets:
- json_data.json
Then in your code you can load this asset as a String:
import 'package:flutter/services.dart' show rootBundle;
Future<String> getJson() {
return rootBundle.loadString('json_data.json');
}
You can decode the JSON with your existing code, but it should be placed in a method body somewhere. You call this getJson function to retrieve the JSON String:
var my_data = json.decode(await getJson());
Alternatively, you could simplify this even further by putting the contents of your JSON file directly into the code as a String, but this may not be possible, it depends on your intended use of this JSON.
const String data = '''
{
"foo" : "bar"
}
''';
var my_data = json.decode(data);
I am using play-ws standalone to consume REST service in scala.
val data = Json.obj("message" -> "How are you?")
wsClient.url("http://localhost:5000/token").post(data).map { response =>
val statusText: String = response.statusText
println(response.body)
}
When i run this, i get the following error,
Cannot find an instance of play.api.libs.json.JsObject to WSBody. Define a BodyWritable[play.api.libs.json.JsObject] or extend play.api.libs.ws.ahc.DefaultBodyWritables
wsClient.url("http://localhost:5000/token").post(data).map { response =>
It tells to define a bodywritable. I have read the documentation but cud't get the "BodyWritable". I am new to scala. Anybody help me please. Thanks in advance.
You need to import BodyWritables for json objects, Add following import statements to your source file
import play.api.libs.ws.JsonBodyReadables._
import play.api.libs.ws.JsonBodyWritables._
For more information have a look at official documentation
The current accepted answer does not work in Scala Play 2.7.x (possibly some earlier versions as well).
I couldn't find it in the docs, but you need to explicitly call asScala on the ws object. For example:
val data = Json.obj("message" -> "How are you?")
ws
.asScala()
.url("http://someurl.com")
.post(data)
.map(response => {
//do something with response
})
Note: this also returns a scala future instead of a java completion stage.
The JSON in question is being read in from a RESTful service, and I would like to print it out (to console, although in .gsp would be fine also) for debugging purposes. Groovy 1.3.7 (current as of August 2011) uses Groovy 1.7.8 (which does not have the JsonOutput introduced in 1.8)
Note I am currently reading it in like this, which I am not convinced is the 'grooviest or grail-est' way to do it - perhaps I could take advantage of the converters and pretty printing if done differently? Code sample would be appreciated.
def serviceURL = new URL(theURL)
def json = new JSONObject(serviceURL.text)
println json
You can pretty print JSON with the toString(int indentFactor) method. Example:
def json = new JSONObject()
json.put('foo', 'bar')
json.put('blat', 'greep')
println json
===>{"foo":"bar","blat","greep"}
println json.toString(4)
===>{
"foo": "bar",
"blat": "greep"
}
You can use grails.converters.JSON (which is the most commonly used library for JSON):
In your config.groovy file, add the line to set prettyPrint to true:
grails.converters.default.pretty.print=true
Then, in your controller:
import grails.converters.*
def serviceURL = new URL(theURL)
def json = JSON.parse(serviceURL.text)
println "JSON RESPONSE: ${json.toString()"
If you're in a Grails controller and plan to render the json, then you use something like this (using Grails 2.3.5):
public prettyJson() {
JSON json = ['status': 'OK'] as JSON
json.prettyPrint = true
json.render response
}
I found that solution here: http://www.intelligrape.com/blog/2012/07/16/rendering-json-with-formatting/
Apart from set default pretty print in Config.groovy, JSON's toString() method accepts one boolean parameter. It controls whether pretty print the result or not.
import grails.converters.*
import my.data.*
def accountJson = Account.get(1001) as JSON
println(accountJson.toString(true))
println(accountJson.toString(false))
Tested in Grails 1.3.9.