GVKun编程网logo

如何将继承的对象字符串化为JSON?(继承string)

13

想了解如何将继承的对象字符串化为JSON?的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于继承string的相关问题,此外,我们还将为您介绍关于ajaxjson对象转化为json字符串、An

想了解如何将继承的对象字符串化为JSON?的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于继承string的相关问题,此外,我们还将为您介绍关于ajax json对象转化为json字符串、Android – Retrofit Gson-如何在JSON响应中将JSON字符串解析为JSON键的对象?、c# – 我如何将json字符串转换为Json对象、ios – 如何将UIImage序列化为JSON?的新知识。

本文目录一览:

如何将继承的对象字符串化为JSON?(继承string)

如何将继承的对象字符串化为JSON?(继承string)

使用JSON.stringify()时,json2.js似乎忽略了父对象的成员。例:

require(''./json2.js'');function WorldObject(type) {        this.position = 4;}function Actor(val) {    this.someVal = 50;}Actor.prototype = new WorldObject();var a = new Actor(2);console.log(a.position);console.log(JSON.stringify(a));

输出为:

4{"someVal":50}

我期望这个输出:

4{"position":0, "someVal":50}

答案1

小编典典

好吧,就是这样,JSON.stringify它不会保留该对象的任何非拥有属性。您可以在此处查看有关其他缺陷和可能的解决方法的有趣讨论。

还要注意,作者不仅记录了问题,而且还编写了一个名为HydrateJS的库,该库可能会对您有所帮助。

这个问题比乍一看要深一些。即使a真正地字符串化为{"position":0,"someVal":50},然后对其进行解析也会创建一个具有所需属性的对象,但该对象既不是Actor的实例,也不是指向WorldObject的原型链接(毕竟,parse方法没有这个信息,因此它不可能以这种方式还原它)。

为了保留原型链,需要一些巧妙的技巧(例如HydrateJS中使用的技巧)。如果这不是您想要的目标,则可能只需要在对对象进行字符串化之前对其进行“展平”。为此,例如,您可以迭代对象的所有属性,而不管它们是否是拥有的,然后重新分配它们(这将确保它们在对象本身上定义,而不仅仅是从原型继承)。

function flatten(obj) {    var result = Object.create(obj);    for(var key in result) {        result[key] = result[key];    }    return result;}

函数的编写方式不会突变原始对象。所以用

console.log(JSON.stringify(flatten(a)));

您将获得所需的输出,并且a将保持不变。

ajax json对象转化为json字符串

ajax json对象转化为json字符串

JSON对象各自之间的转换
        JSON.parse(jsonstr); //可以将json字符串转换成json对象   
        JSON.stringify(jsonobj); //可以将json对象转换成json对符串

Android – Retrofit Gson-如何在JSON响应中将JSON字符串解析为JSON键的对象?

Android – Retrofit Gson-如何在JSON响应中将JSON字符串解析为JSON键的对象?

这是我的JSON响应:

{
      "id": 2,
      "name": "Test",
      "content": "{\"type\": \"status\", \"text\": \"Lorem ipsum dummy text.\", \"id\": 1}"
}

这些是模型结构:

class TestModel {
    public int id;
    public String name;
    public Content content;
}

class Content {
    public int id;
    public String status;
    public String text;
}

我想使用Retrofit和GsonConvertor将内容的值直接解析到我的Content模型对象中.但是目前,我将其解析为String值,而不是使用Gson.fromJson()转换为我的Content模型对象.是否有任何解决方案可以获得我的预期结果?

当我以前使用GsonConverterFactory解析它时,Retrofit在onFailure方法中给出了回调,但有以下异常:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 4 column 19 path $.data[0].content

解决方法:

问题在于JSON响应,它不在correct JSON format中.“content”字段应该是一个对象,而不是一个字符串:

{
    "id": 2,
    "name": "Test",
    "content": {
        "type": "status",
        "text": "Lorem ipsum dummy text.",
        "id": 1
    }
}

这将允许gson.fromJson(response,TestModel.class)或带有GsonConverterFactory的RetroFit将您的响应正确解析为相应的对象.

当然,这仅适用于您能够更改正在接收的JSON响应的情况.如果没有,首先要确保控制响应的人知道他们做错了.如果没有任何变化,那么您应该能够通过将TestModel中的内容更改为String来解决此问题:

class TestModel {
    public int id;
    public String name;
    public String content;
}

class Content {
    public int id;
    public String type;
    public String text;
}

然后分别解析每个对象:

TestModel testModel = gson.fromJson(response, TestModel.class);
Content content = gson.fromJson(testModel.content, Content.class);

如果无法更改响应,则另一个选项是为Content对象创建TypeAdapter

public class ContentAdapter extends TypeAdapter<Content> {

    @Override
    public void write(JsonWriter out, Content value) throws IOException {
        // Todo: Writer implementation
    }

    @Override
    public Content read(JsonReader in) throws IOException {
        if(in.peek() != JsonToken.NULL) {
            return fromJson(in.nextString());
        } else {
            in.nextNull();
            return null;
        }
    }

}

然后将TypeAdapter添加到您的GSON实现:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Content.class, new ContentAdapter()).create();

c# – 我如何将json字符串转换为Json对象

c# – 我如何将json字符串转换为Json对象

参见英文答案 > Convert JSON String to JSON Object c#                                    7个
我有json字符串的方法,我想将json字符串转换为json对象.我试过下面的方法它显示内存超出如何解决错误.
我试过这个字符串抛出ajax它的工作正常.但我如何从后端的字符串转换为数据表.任何建议.
我的代码.

public ActionResult JosnString()
        {

      string str = "{\"delivery\": [{\"status\": 2,\"resp_msg\": \"5.4.1 [renard.allenll@transdev.com]: Recipient address rejected: Access denied [HE1EUR02FT054.eop-EUR02.prod.protection.outlook.com]\",\"mail_from\": \"vision@transdev.com\",\"time_started\": 1539808420,\"time_finished\": 1539808426,\"resp_code_description\": \"The requested command Failed because the user's mailBox was unavailable (for example because it was not found,or because the command was rejected for policy reasons).\",\"sender_id\": 9007074,\"campaign_id\": \"\",\"rcpt_to\": \"renard.allenll@transdev.com\",\"tries\": 0,\"resp_code\": 550,\"tracking_id\": \"2939c3ea-59e8-4019-9f4b-4cd4214254b4\",\"resp_class\": 10,\"subject\": \"Las Vegas Notification - Passenger Fall- No Injury (Auto Email \u2013 Do Not Repl (#718701)\"},{\"status\": 2,\"resp_msg\": \"5.4.1 [Theodrick.mccullom@transdev.com]: Recipient address rejected: Access denied [HE1EUR02FT042.eop-EUR02.prod.protection.outlook.com]\",\"time_started\": 1539809940,\"time_finished\": 1539809944,\"rcpt_to\": \"theodrick.mccullom@transdev.com\",\"tracking_id\": \"2c75c0e1-cf9c-4c92-9d11-e6cebfc28300\",\"subject\": \"Las Vegas Notification - Safety- Passenger Event (Auto Email \u2013 Do Not Reply) (#724957)\"},\"resp_msg\": \"5.4.1 [tricia.mumford@transdev.com]: Recipient address rejected: Access denied [VE1EUR02FT003.eop-EUR02.prod.protection.outlook.com]\",\"time_started\": 1539810919,\"time_finished\": 1539810926,\"rcpt_to\": \"tricia.mumford@transdev.com\",\"tracking_id\": \"2f7a87e4-513e-4358-b1b6-bb8febdff35d\",\"subject\": \"SV Alert Alert (#725159)\"},\"resp_msg\": \"5.4.1 [Theodrick.mccullom@transdev.com]: Recipient address rejected: Access denied [HE1EUR02FT033.eop-EUR02.prod.protection.outlook.com]\",\"time_started\": 1539815408,\"time_finished\": 1539815412,\"tracking_id\": \"e9bb47c0-22d5-4781-ac2a-9bef56232255\",\"subject\": \"Las Vegas Notification - Safety- Accident with no injuries (Auto Email \u2013 Do (#733279)\"},\"resp_msg\": \"5.4.1 [francisco.sanchez@transdev.com]: Recipient address rejected: Access denied [HE1EUR02FT026.eop-EUR02.prod.protection.outlook.com]\",\"time_started\": 1539815465,\"time_finished\": 1539815469,\"rcpt_to\": \"francisco.sanchez@transdev.com\",\"tracking_id\": \"c5baf56c-89da-4388-a692-da2b84862f0a\",\"subject\": \"Malfunctioning GPS,please reboot this these device(s). (#733299)\"},\"resp_msg\": \"5.4.1 [carl.parr@transdev.com]: Recipient address rejected: Access denied [HE1EUR02FT019.eop-EUR02.prod.protection.outlook.com]\",\"time_started\": 1539816062,\"time_finished\": 1539816067,\"rcpt_to\": \"carl.parr@transdev.com\",\"tracking_id\": \"e6299d04-5aac-43d3-8593-1a3c548e336f\",\"subject\": \"SV Alert Alert (#733431)\"},\"resp_msg\": \"5.4.1 [Theodrick.mccullom@transdev.com]: Recipient address rejected: Access denied [HE1EUR02FT038.eop-EUR02.prod.protection.outlook.com]\",\"time_started\": 1539816315,\"time_finished\": 1539816318,\"tracking_id\": \"ea9caff3-364e-4a32-8365-98a897a6bbc5\",\"subject\": \"Las Vegas Notification - Safety- Accident with no injuries (Auto Email \u2013 Do (#734371)\"},\"resp_msg\": \"5.4.1 [francisco.sanchez@transdev.com]: Recipient address rejected: Access denied [VE1EUR02FT035.eop-EUR02.prod.protection.outlook.com]\",\"time_started\": 1539820874,\"time_finished\": 1539820877,\"tracking_id\": \"b81e47e5-5211-425a-a7be-5b75379bf3b1\",please reboot this these device(s). (#735305)\"},\"resp_msg\": \"5.4.1 [francisco.sanchez@transdev.com]: Recipient address rejected: Access denied [VE1EUR02FT053.eop-EUR02.prod.protection.outlook.com]\",\"time_started\": 1539826279,\"time_finished\": 1539826283,\"tracking_id\": \"c2b7a520-a994-49a6-b34b-96113f5960d5\",please reboot this these device(s). (#735539)\"},\"resp_msg\": \"5.4.1 [Ramona.Trotter@transdev.com]: Recipient address rejected: Access denied [HE1EUR02FT023.eop-EUR02.prod.protection.outlook.com]\",\"time_started\": 1539829584,\"time_finished\": 1539829587,\"rcpt_to\": \"ramona.trotter@transdev.com\",\"tracking_id\": \"264645cd-0792-445b-9fd4-1cccd0746cfb\",\"subject\": \"Driver dispatch Log Entries (Auto Email \u2013 Do Not Reply) (#736221)\"}],\"last_update_time\": 1540421479.703088}";
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                DataSet dt = (DataSet)JsonConvert.DeserializeObject(str,(typeof(DataSet)));
            return new EmptyResult();
}

解决方法

你可以试试这个

string str = "{ 'context_name': { 'lower_bound': 'value','pper_bound': 'value','values': [ 'value1','valueN' ] } }";
    JavaScriptSerializer j = new JavaScriptSerializer();
    object a = j.Deserialize(str,typeof(object));

ios – 如何将UIImage序列化为JSON?

ios – 如何将UIImage序列化为JSON?

我在用

imageData = UIImagePNGRepresentation(imgvw.image);

并张贴

[dic setobject:imagedata forKey:@"image"];

NSData * data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:& theError];

由于未捕获的异常’NSinvalidargumentexception’,现在应用程序正在崩溃终止应用程序,原因:’JSON写入中的无效类型(NSConcreteMutableData)

解决方法

您需要将UIImage转换为NSData,然后将该NSData转换为Nsstring,它将是您数据的base64字符串表示形式.

从NSData *获得Nsstring *后,您可以将其添加到密钥@“image”的字典中

要将NSData转换为base64类型Nsstring *,请参阅以下链接:
How do I do base64 encoding on iphone-sdk?

以更伪的方式,该过程将如下所示

UIImage *my_image; //your image handle
NSData *data_of_my_image = UIImagePNGRepresentation(my_image);
Nsstring *base64StringOf_my_image = [data_of_my_image convertToBase64String];

//Now you can add it to your dictionary
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setobject:base64StringOf_my_image forKey:@"image"];

if ([NSJSONSerialization isValidJSONObject:dict]) //perform a check
{
        NSLog(@"valid object for JSON");
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];


        if (error!=nil) {
            NSLog(@"Error creating JSON Data = %@",error);
        }
        else{
            NSLog(@"JSON Data created successfully.");
        }
}
else{
        NSLog(@"not a valid object for JSON");
    }

今天的关于如何将继承的对象字符串化为JSON?继承string的分享已经结束,谢谢您的关注,如果想了解更多关于ajax json对象转化为json字符串、Android – Retrofit Gson-如何在JSON响应中将JSON字符串解析为JSON键的对象?、c# – 我如何将json字符串转换为Json对象、ios – 如何将UIImage序列化为JSON?的相关知识,请在本站进行查询。

本文标签: