简体   繁体   中英

What is the Python equivalent of StringEntity in Java?

I have the following class in Java:

class JsonEntity extends StringEntity {
    private final String string;

    public JsonEntity(String string, Charset charset) {
        super(string, ContentType.create(ContentType.APPLICATION_JSON.getMimeType(), charset));
        this.string = string
}

I have no clue how to implement the above code in Python 2.7. Is there any way I can achieve this?

I don' know if I exactly get your need, however if you need to save as JSON with a particular charset in python you can do something like this:

import json 
json_string = json.dumps("your string even with wierd symbols", ensure_ascii=False).encode('utf8')

NB: you can change utf8 with other charsets.

EDIT: Anyway if you need to extend something to actually implement your json reader/writer you can extend JSONEncoder: https://docs.python.org/2.6/library/json.html#json.JSONEncoder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM