Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

spring mvc - Dart: convert Map to JSON with all elements quoted

I'm serializing a form in Dart into JSON then posting it to a Spring MVC backend using Jackson to deserialize the JSON.

In dart, if I print out the JSON, I'm getting:

{firstName: piet, lastName: venter}

Jackson doesn't like the data in this format, it returns a status 400 and The request sent by the client was syntactically incorrect.

If I put quotes around all the fields, Jackson accepts the data and I get a response back.

{"firstName": "piet", "lastName": "venter"}

In dart I build a Map<String, String> data = {}; then loop through all form fields and do data.putIfAbsent(input.name, () => input.value);

Now when I call data.toString(), I get the unquoted JSON which I'm guessing is invalid JSON.

If I import 'dart:convert' show JSON; and try JSON.encode(data).toString(); I get the same unquoted JSON.

Manually appending double-quotes seems to work:

data.putIfAbsent(""" + input.name + """, () => """ + input.value + """);

On the Java side there's no rocket science:

@Controller
@RequestMapping("/seller")
@JsonIgnoreProperties(ignoreUnknown = true)
public class SellerController {

    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST, headers = {"Content-Type=application/json"})
    public Seller createSeller(@RequestBody Seller sellerRequest){

So my question, is there a less hacky way in Dart to build quoted JSON (other than manually escaping quotes and adding quotes manually) that Jackson expects? Can Jackson be configured to allow unquoted JSON ?

question from:https://stackoverflow.com/questions/29294019/dart-convert-map-to-json-with-all-elements-quoted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import 'dart:convert';
...
json.encode(data); // JSON.encode(data) in Dart 1.x

always resulted in quoted JSON for me.
You don't need to call toString()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...