How can I prevent SerializeJSON from changing Yes/No/True/False strings to boolean?

后端 未结 6 577
失恋的感觉
失恋的感觉 2020-12-20 12:19

I have a data struct being stored in JSON format, converted using the serializeJSON function. The problem I am running into is that strings that can be boolean in CF such as

相关标签:
6条回答
  • 2020-12-20 12:36

    I'd try javacasting it: key = javacast("string", "yes"). That should force CF to recognize it as a string rather than as a boolean.

    0 讨论(0)
  • 2020-12-20 12:37

    Use JsonSerializer.cfc by Ben Nadel

    0 讨论(0)
  • 2020-12-20 12:46

    I believe that your or any similar "string forcing" workaround is the only possible way to prevent such behavior in Adobe CF for now.

    BTW, Railo works as expected with your example. Here is the output:

    Yes
    {"STR":"Yes"}
    Yes 
    

    It is also works same way for the numbers with trailing zeros.

    0 讨论(0)
  • 2020-12-20 12:51

    it's hacky, but if you conditionally output yes and no as "_yes_" and "_no_" (using a switch statement and then after serialising the JSON to a string, do a search and replace, it works.

    raw_json=serializeJSON(object);
    raw_json=ReplaceNoCase(raw_json,':"_Yes_"',':"Yes"',"ALL"); 
    raw_json=ReplaceNoCase(raw_json,':"_No_"',':"No"',"ALL");
    

    at least CF is consistantly frustrating with this, true & false get converted to yes no when you round trip the data

    0 讨论(0)
  • 2020-12-20 12:51

    I know this answer would not have worked when the question was asked, but as this seems to be the one that people are finding when researching this issue, I thought it would be good to update with a new fix.

    For those on CF2016, Adobe has implemented a new function to help fix this issue. This would be preferable to adding a space to the front of strings, though that would still need to be the work around for releases before CF2016 as described by Sergii.

    For Structs in CF2016:

    Use the struct function, setMetadata, to specify the metadata.

    The metadata is a struct where each key is struct key and the value of each key specifies the information on how to serialize in JSON.

    The value of the key can be a string or a struct.

    Value as string

    metadata = {firstname: "string"}};

    Value as struct

    metadata = {firstname: {type: "string"}};

    Example:

    <cfscript>
           example = structnew();
           example.firstname = "Yes";
           example.lastname = "Man";
           // changing the default serialization by specifying the type of "firstname" as string
           metadata = {firstname: {type:"string"}};
           example.setMetadata(metadata);
           writeoutput(SerializeJSON(example));
    </cfscript>

    For Queries in CF11+: Adobe reports that they've fixed this issue.

    0 讨论(0)
  • 2020-12-20 12:52

    Adding an extra space in the string to prevent it from being converted to boolean, then trim at a later stage.

    0 讨论(0)
提交回复
热议问题