How can I JSON.stringify a Collection in Dart - json

How can I made a JSON string out of a collection in dart, as I can do it with Maps. The docs say I can pass a map or a an array into the JSON.stringify() method. But there are no Array data type in Dart and passing a collection gives me an exception.
I've a naive workaround, but I wonder if there will be a better way to do this:
String s = '[';
bool first=true;
_set.forEach(function(item){
if (first) {
first = false;
} else {
s+=',';
}
s += JSON.stringify(item);
});
s +=']';
print(s);
return s;

In Dart, you can get a JSON String out of an Object using the JsonEncoder's convert method. Here is an example:
import 'dart:convert';
void main() {
final jsonEncoder = JsonEncoder();
final collection1 = List.from([1, 2, 3]);
print(jsonEncoder.convert(collection1)); // prints [1,2,3]
final collection2 = List.from(['foo', 'bar', 'dart']);
print(jsonEncoder.convert(collection2)); // prints ["foo","bar","dart"]
final object = {'a': 1, 'b': 2};
print(jsonEncoder.convert(object)); // prints {"a":1,"b":2}
}

Passing a list works for me:
in the Dart VM importing dart-sdk/lib/frog/server/dart_json.dart
in Dartium importing json:dart
using this code:
void main() {
var list = new List.from(["a","b","c"]);
print(JSON.stringify(list));
}
prints this JSON snippet:
["a","b","c"]
Doesn't work for new Set.from(...) which is expected, given that JSON only deals in maps and lists.

Related

How to send List of objects in a multipart request in flutter?

I want to send a List of ManageTagModel in a multipart request along with other models and files..
I am not certain of how to send this List of model..
This is my code for sending the multipart request without the List:
var uri = Uri.parse(...);
final request = http.MultipartRequest('Post', uri);
request.fields['Id'] = '3';
request.fields['Name'] = siteModel.name;
request.fields['MapAddress'] = siteModel.mapAddress;
request.fields['Country'] = siteModel.country;
request.fields['City'] = siteModel.city;
request.fields['CategoryNb'] = siteModel.categoryNb;
request.fields['UserId'] = userId;
request.fields['Caption'] = caption;
for (File i in
multipleFiles) {
final mimeTypeData =
lookupMimeType(i.path, headerBytes: [0xFF, 0xD8]).split('/');
print("IMAGE: " + i.path);
// Attach the file in the request
final file = await http.MultipartFile.fromPath('files', i.path);
print(mimeTypeData[0] + " mimeTypeData[0]");
print(mimeTypeData[1] + " mimeTypeData[1]");
request.files.add(file);
this is my model:
import 'dart:convert';
class ManageTagModel {
String posX;
String posY;
String postOrder;
String tagger;
String tagged;
ManageTagModel(
{this.posX, this.posY, this.postOrder, this.tagger, this.tagged});
//Flutter way of creating a constructor
factory ManageTagModel.fromJson(Map<String, dynamic> json) => ManageTagModel(
posX: json['PosX'],
posY: json['PosY'],
postOrder: json['PostOrder'],
tagged: json['Tagged'],
tagger: json['Tagger']);
Map<String, dynamic> toMap() {
return {
"PosX": posX,
"PosY": posY,
"PostOrder": postOrder,
"Tagger": tagger,
"Tagged": tagged
};
}
}
List<ManageTagModel> fromJson(String jsonData) {
// Decode json to extract a map
final data = json.decode(jsonData);
return List<ManageTagModel>.from(
data.map((item) => ManageTagModel.fromJson(item)));
}
String toJson(ManageTagModel data) {
// First we convert the object to a map
final jsonData = data.toMap();
// Then we encode the map as a JSON string
return json.encode(jsonData);
}
List encodeToJson(List<ManageTagModel> list) {
List jsonList = List();
list.map((item) => jsonList.add(item.toMap())).toList();
return jsonList;
}
My backend c# method has a parameter List
Any help is appreciated!!
I'm pretty sure I'm quite late here and you might have already found a solution. I have gone through multiple threads and didn't actually find any answers but discovered myself out of frustration and thought to myself that the answer actually is still not out there for any other lost human soul. So here is my solution for anyone still stuck here which is quite intuitive.
You simply have to add all the elements of the list to the request as "files" instead of "fields". But instead of fromPath() method, you have to use fromString().
final request = http.MultipartRequest('Post', uri);
List<String> ManageTagModel = ['xx', 'yy', 'zz'];
for (String item in ManageTagModel) {
request.files.add(http.MultipartFile.fromString('manage_tag_model', item));
}
This worked out for me and I hope it works for you too.
if the data was not string
for (int item in _userData['roles']) {
request.files
.add(http.MultipartFile.fromString('roles', item.toString()));
}

Flutter - Dart variables lost and keep getting reinitialized

I'm trying out things with Flutter right now. But my variables keep getting reinitialised when accessed from another class.
I'm using json parsing and i need two parts of my request. The "Relatorio" part and the "Mensagem" part.
to parse this json i'm doing this:
List<RelatorioProdutos> parseRelatorioPorProduto(String responseBody) {
final parsed = json.decode(responseBody);
var relatorio = parsed['Relatorio'];
var mensagem = parsed['Mensagem'];
print (mensagem); // Here the variable returns well,
//but when i need it in other class i receive null.
return relatorio.map<RelatorioProdutos>((json) => new RelatorioProdutos.fromJson(json)).toList();
}
class RelatorioProdutos {
String CodigoProduto;
var QtdVendida;
var TotalVendas;
String Descricao;
RelatorioProdutos({this.CodigoProduto, this.QtdVendida, this.TotalVendas, this.Descricao,});
factory RelatorioProdutos.fromJson(Map json) {
//returns a List of Maps
return new RelatorioProdutos(
CodigoProduto: json['CodigoProduto'] as String,
QtdVendida: json['QtdVendida'],
TotalVendas: json['TotalVendas'],
Descricao: json['Descricao'] as String,
);
}
}
I want to use this 'mensagem' variable in another class to show the error for user, but i always receive 'null'.
i already tried setState but it reloads my json and i dont want to request the RestServer again.
Thanks from now!
If I understand correctly, you want to access a local variable of a function from another class. I don't think it's possible.
One way to do it, would be to wrap your response in another object containing the response, and this variable:
List<Response<RelatorioProdutos>> parseRelatorioPorProduto(
String responseBody) {
final parsed = json.decode(responseBody);
var relatorio = parsed['Relatorio'];
var mensagem = parsed['Mensagem'];
print(mensagem); // Here the variable returns well,
//but when i need it in other class i receive null.
return relatorio
.map((json) => new Response<RelatorioProdutos>(
new RelatorioProdutos.fromJson(json), mensagem))
.toList();
}
class RelatorioProdutos {
String CodigoProduto;
var QtdVendida;
var TotalVendas;
String Descricao;
RelatorioProdutos({
this.CodigoProduto,
this.QtdVendida,
this.TotalVendas,
this.Descricao,
});
factory RelatorioProdutos.fromJson(Map json) {
//returns a List of Maps
return new RelatorioProdutos(
CodigoProduto: json['CodigoProduto'] as String,
QtdVendida: json['QtdVendida'],
TotalVendas: json['TotalVendas'],
Descricao: json['Descricao'] as String,
);
}
}
class Response<T> {
const Response(
this.value,
this.errorMessage,
);
final T value;
final String errorMessage;
bool get hasError => errorMessage != null;
}
In this example I created a Response object that can contains both the response value and an error message.
In the parseRelatorioPorProduto, instead of returning the relatorio, I changed the return type to Response<RelatorioProdutos> in order to have access to the value and the error message from any class which call this function.
Thanks Letsar, i tried yout ideia but i get a lot of others erros.
To solve this problem i used this:
List<RelatorioProdutos> parseRelatorioPorProduto(String responseBody) {
final parsed = json.decode(responseBody);
var relatorio = parsed['Relatorio'];
var mensagem = parsed['Mensagem'];
if(mensagem[0].toString().substring(16,17) == "0"){
List<RelatorioProdutos> asd = new List();
RelatorioProdutos aimeudeus = new RelatorioProdutos(Descricao: mensagem[0].toString(), CodigoProduto: "a", TotalVendas: 0, QtdVendida: 0);
asd.add(aimeudeus);
return asd;
}else{
return relatorio.map<RelatorioProdutos>((json) => new RelatorioProdutos.fromJson(json)).toList();
}
}

Can't iterate through JSON object

I'm pulling a JSON request from the politifact API:
request('http://politifact.com/api/v/2/statement/?format=[JSON]&order_by=-ruling_date&limit=1')
.then(({
data
}) => {
newArticles = extractListingsFromJSON(data);
and parsing it with a function that the JSON is passed to
function extractListingsFromJSON(json) {
var jsonObject = json.objects
Outputs entire objects array
var headline = jsonObject[0].facebook_headline
console.log("headline:\n" + headline)
Outputs headline from Objects[0]
This works as intended. However, when I try to iterate through the objects array like so:
for (var attr in jsonObject) {
console.log(attr+": "+jsonObject.facebook_headline);
}
Outputs "0: undefined"
I also tried:
console.log(attr+": "+jsonObject[facebook_headline];
Outputs nothing
As you mentioned yourself jsonObject is an array.
json.objects.forEach(function (i) {
console.log(i.facebook_headline)
})
You still need the attr key to iterate through the jsonObject. Try doing attr+" :"+jsonObject[attr].facebook_headline
instead.

Use Jackson To Stream Parse an Array of Json Objects

I have a file that contains a json array of objects:
[
{
"test1": "abc"
},
{
"test2": [1, 2, 3]
}
]
I wish to use use Jackson's JsonParser to take an inputstream from this file, and at every call to .next(), I want it to return an object from the array until it runs out of objects or fails.
Is this possible?
Use case:
I have a large file with a json array filled with a large number of objects with varying schemas. I want to get one object at a time to avoid loading everything into memory.
EDIT:
I completely forgot to mention. My input is a string that is added to over time. It slowly accumulates json over time. I was hoping to be able to parse it object by object removing the parsed object from the string.
But I suppose that doesn't matter! I can do this manually so long as the jsonParser will return the index into the string.
Yes, you can achieve this sort of part-streaming-part-tree-model processing style using an ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
JsonParser parser = mapper.getFactory().createParser(new File(...));
if(parser.nextToken() != JsonToken.START_ARRAY) {
throw new IllegalStateException("Expected an array");
}
while(parser.nextToken() == JsonToken.START_OBJECT) {
// read everything from this START_OBJECT to the matching END_OBJECT
// and return it as a tree model ObjectNode
ObjectNode node = mapper.readTree(parser);
// do whatever you need to do with this object
}
parser.close();
What you are looking for is called Jackson Streaming API. Here is a code snippet using Jackson Streaming API that could help you to achieve what you need.
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createJsonParser(new File(yourPathToFile));
JsonToken token = parser.nextToken();
if (token == null) {
// return or throw exception
}
// the first token is supposed to be the start of array '['
if (!JsonToken.START_ARRAY.equals(token)) {
// return or throw exception
}
// iterate through the content of the array
while (true) {
token = parser.nextToken();
if (!JsonToken.START_OBJECT.equals(token)) {
break;
}
if (token == null) {
break;
}
// parse your objects by means of parser.getXxxValue() and/or other parser's methods
}
This example reads custom objects directly from a stream:
source is a java.io.File
ObjectMapper mapper = new ObjectMapper();
JsonParser parser = mapper.getFactory().createParser( source );
if ( parser.nextToken() != JsonToken.START_ARRAY ) {
throw new Exception( "no array" );
}
while ( parser.nextToken() == JsonToken.START_OBJECT ) {
CustomObj custom = mapper.readValue( parser, CustomObj.class );
System.out.println( "" + custom );
}
This is a late answer that builds on Ian Roberts' answer. You can also use a JsonPointer to find the start position if it is nested into a document. This avoids custom coding the slightly cumbersome streaming token approach to get to the start point. In this case, the basePath is "/", but it can be any path that JsonPointer understands.
Path sourceFile = Paths.get("/path/to/my/file.json");
// Point the basePath to a starting point in the file
JsonPointer basePath = JsonPointer.compile("/");
ObjectMapper mapper = new ObjectMapper();
try (InputStream inputSource = Files.newInputStream(sourceFile);
JsonParser baseParser = mapper.getFactory().createParser(inputSource);
JsonParser filteredParser = new FilteringParserDelegate(baseParser,
new JsonPointerBasedFilter(basePath), false, false);) {
// Call nextToken once to initialize the filteredParser
JsonToken basePathToken = filteredParser.nextToken();
if (basePathToken != JsonToken.START_ARRAY) {
throw new IllegalStateException("Base path did not point to an array: found "
+ basePathToken);
}
while (filteredParser.nextToken() == JsonToken.START_OBJECT) {
// Parse each object inside of the array into a separate tree model
// to keep a fixed memory footprint when parsing files
// larger than the available memory
JsonNode nextNode = mapper.readTree(filteredParser);
// Consume/process the node for example:
JsonPointer fieldRelativePath = JsonPointer.compile("/test1");
JsonNode valueNode = nextNode.at(fieldRelativePath);
if (!valueNode.isValueNode()) {
throw new IllegalStateException("Did not find value at "
+ fieldRelativePath.toString()
+ " after setting base to " + basePath.toString());
}
System.out.println(valueNode.asText());
}
}

Antlr4 StringTemplate not compatible with Json.net dynamic items

I would like to read a dynamic object from a json file and then use this in a stringTemplate.
The following code works.
dynamic data = new { bcName = "Lixam B.V", periodName = "July 2013" };
var engine = new Template("<m.bcName> <m.periodName>");
engine.Add("m", data);
engine.Render().Should().Be("Lixam B.V July 2013");
The following code fails
var json = "{bcName : 'Lixam B.V', periodName : 'July 2013'}";
dynamic data = JsonConvert.DeserializeObject(json);
string name = (data.bcName);
name.Should().Be("Lixam B.V"); // this passes
var engine = new Template("<m.bcName> <m.periodName>");
engine.Add("m", data);
engine.Render().Should().Be("Lixam B.V July 2013"); //fails
Is there another way to configure JsonConverter to be compatible with StringTemplate
You need to create an IModelAdaptor for whatever the compiled type representing dynamic is, and register it using TemplateGroup.RegisterModelAdaptor.
Inspired on Mr. Harwell's answer, I've implemented an IModelAdaptor that enable the usage of Newtonsoft.Json parsed objects.
Here it goes:
internal class JTokenModelAdaptor : Antlr4.StringTemplate.IModelAdaptor
{
public object GetProperty(
Antlr4.StringTemplate.Interpreter interpreter,
Antlr4.StringTemplate.TemplateFrame frame,
object obj,
object property,
string propertyName)
{
var token = (obj as JToken)?.SelectToken(propertyName);
if (token == null)
return null;
if (token is JValue)
{
var jval = token as JValue;
return jval.Value;
}
return token;
}
}
You just need to register the adaptor in your template group, like this:
template.Group.RegisterModelAdaptor(typeof(JToken), new JTokenModelAdaptor());