How to convert a file to a String which is accepted in JSON?












0















I am trying to create gists in Github via REST ASSURED.



To create a gist a need to pass file names and their contents.



Now, the content of the file is something which is being rejected by the API.



Example:



{
"description": "Hello World Examples",
"public": true,
"files": {
"hello_world.rb": {
"content": "class HelloWorldn def initialize(name)n @name = name.capitalizen endn def sayHin puts "Hello !"n endnendnnhello = HelloWorld.new("World")nhello.sayHi"
},
"hello_world.py": {
"content": "class HelloWorld:nn def init(self, name):n self.name = name.capitalize()n n def sayHi(self):n print "Hello " + self.name + "!"nnhello = HelloWorld("world")nhello.sayHi()"
},
"hello_world_ruby.txt": {
"content": "Run ruby hello_world.rb to print Hello World"
},
"hello_world_python.txt": {
"content": "Run python hello_world.py to print Hello World"
}
}


This is how the the API wants the JSON to be, I could get this via my code:



{
"description": "Happy World",
"public": true,
"files": {
"sid.java": {
"content": "Ce4z5e22ta"
},
"siddharth.py": {
"content": "def a:
if sidh>kundu:
sid==kundu
else:
kundu==sid

"
}
}
}


So the change in the indentations is causing GitHUb API to fail this with 400 error. Can someone please help?










share|improve this question




















  • 1





    pretty sure JSON does not allow multiline strings stackoverflow.com/a/2392888/7927820

    – Hanjun Chen
    Nov 23 '18 at 14:28











  • It seems you're generating JSON by concatenating string parts. Don't do that. Use an actual JSON library to generate JSON nodes, or even better, to map objects to JSON. The JSON library will generate valid JSON by escaping everything that needs to be escaped.

    – JB Nizet
    Nov 23 '18 at 14:29













  • You are missing one final closing bracket in your first code snippet -- is that intentional? Because that's not a valid JSON text.

    – amn
    Nov 23 '18 at 14:38
















0















I am trying to create gists in Github via REST ASSURED.



To create a gist a need to pass file names and their contents.



Now, the content of the file is something which is being rejected by the API.



Example:



{
"description": "Hello World Examples",
"public": true,
"files": {
"hello_world.rb": {
"content": "class HelloWorldn def initialize(name)n @name = name.capitalizen endn def sayHin puts "Hello !"n endnendnnhello = HelloWorld.new("World")nhello.sayHi"
},
"hello_world.py": {
"content": "class HelloWorld:nn def init(self, name):n self.name = name.capitalize()n n def sayHi(self):n print "Hello " + self.name + "!"nnhello = HelloWorld("world")nhello.sayHi()"
},
"hello_world_ruby.txt": {
"content": "Run ruby hello_world.rb to print Hello World"
},
"hello_world_python.txt": {
"content": "Run python hello_world.py to print Hello World"
}
}


This is how the the API wants the JSON to be, I could get this via my code:



{
"description": "Happy World",
"public": true,
"files": {
"sid.java": {
"content": "Ce4z5e22ta"
},
"siddharth.py": {
"content": "def a:
if sidh>kundu:
sid==kundu
else:
kundu==sid

"
}
}
}


So the change in the indentations is causing GitHUb API to fail this with 400 error. Can someone please help?










share|improve this question




















  • 1





    pretty sure JSON does not allow multiline strings stackoverflow.com/a/2392888/7927820

    – Hanjun Chen
    Nov 23 '18 at 14:28











  • It seems you're generating JSON by concatenating string parts. Don't do that. Use an actual JSON library to generate JSON nodes, or even better, to map objects to JSON. The JSON library will generate valid JSON by escaping everything that needs to be escaped.

    – JB Nizet
    Nov 23 '18 at 14:29













  • You are missing one final closing bracket in your first code snippet -- is that intentional? Because that's not a valid JSON text.

    – amn
    Nov 23 '18 at 14:38














0












0








0








I am trying to create gists in Github via REST ASSURED.



To create a gist a need to pass file names and their contents.



Now, the content of the file is something which is being rejected by the API.



Example:



{
"description": "Hello World Examples",
"public": true,
"files": {
"hello_world.rb": {
"content": "class HelloWorldn def initialize(name)n @name = name.capitalizen endn def sayHin puts "Hello !"n endnendnnhello = HelloWorld.new("World")nhello.sayHi"
},
"hello_world.py": {
"content": "class HelloWorld:nn def init(self, name):n self.name = name.capitalize()n n def sayHi(self):n print "Hello " + self.name + "!"nnhello = HelloWorld("world")nhello.sayHi()"
},
"hello_world_ruby.txt": {
"content": "Run ruby hello_world.rb to print Hello World"
},
"hello_world_python.txt": {
"content": "Run python hello_world.py to print Hello World"
}
}


This is how the the API wants the JSON to be, I could get this via my code:



{
"description": "Happy World",
"public": true,
"files": {
"sid.java": {
"content": "Ce4z5e22ta"
},
"siddharth.py": {
"content": "def a:
if sidh>kundu:
sid==kundu
else:
kundu==sid

"
}
}
}


So the change in the indentations is causing GitHUb API to fail this with 400 error. Can someone please help?










share|improve this question
















I am trying to create gists in Github via REST ASSURED.



To create a gist a need to pass file names and their contents.



Now, the content of the file is something which is being rejected by the API.



Example:



{
"description": "Hello World Examples",
"public": true,
"files": {
"hello_world.rb": {
"content": "class HelloWorldn def initialize(name)n @name = name.capitalizen endn def sayHin puts "Hello !"n endnendnnhello = HelloWorld.new("World")nhello.sayHi"
},
"hello_world.py": {
"content": "class HelloWorld:nn def init(self, name):n self.name = name.capitalize()n n def sayHi(self):n print "Hello " + self.name + "!"nnhello = HelloWorld("world")nhello.sayHi()"
},
"hello_world_ruby.txt": {
"content": "Run ruby hello_world.rb to print Hello World"
},
"hello_world_python.txt": {
"content": "Run python hello_world.py to print Hello World"
}
}


This is how the the API wants the JSON to be, I could get this via my code:



{
"description": "Happy World",
"public": true,
"files": {
"sid.java": {
"content": "Ce4z5e22ta"
},
"siddharth.py": {
"content": "def a:
if sidh>kundu:
sid==kundu
else:
kundu==sid

"
}
}
}


So the change in the indentations is causing GitHUb API to fail this with 400 error. Can someone please help?







java json






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 14:37









amn

3,95553262




3,95553262










asked Nov 23 '18 at 14:24









Siddharth KunduSiddharth Kundu

1




1








  • 1





    pretty sure JSON does not allow multiline strings stackoverflow.com/a/2392888/7927820

    – Hanjun Chen
    Nov 23 '18 at 14:28











  • It seems you're generating JSON by concatenating string parts. Don't do that. Use an actual JSON library to generate JSON nodes, or even better, to map objects to JSON. The JSON library will generate valid JSON by escaping everything that needs to be escaped.

    – JB Nizet
    Nov 23 '18 at 14:29













  • You are missing one final closing bracket in your first code snippet -- is that intentional? Because that's not a valid JSON text.

    – amn
    Nov 23 '18 at 14:38














  • 1





    pretty sure JSON does not allow multiline strings stackoverflow.com/a/2392888/7927820

    – Hanjun Chen
    Nov 23 '18 at 14:28











  • It seems you're generating JSON by concatenating string parts. Don't do that. Use an actual JSON library to generate JSON nodes, or even better, to map objects to JSON. The JSON library will generate valid JSON by escaping everything that needs to be escaped.

    – JB Nizet
    Nov 23 '18 at 14:29













  • You are missing one final closing bracket in your first code snippet -- is that intentional? Because that's not a valid JSON text.

    – amn
    Nov 23 '18 at 14:38








1




1





pretty sure JSON does not allow multiline strings stackoverflow.com/a/2392888/7927820

– Hanjun Chen
Nov 23 '18 at 14:28





pretty sure JSON does not allow multiline strings stackoverflow.com/a/2392888/7927820

– Hanjun Chen
Nov 23 '18 at 14:28













It seems you're generating JSON by concatenating string parts. Don't do that. Use an actual JSON library to generate JSON nodes, or even better, to map objects to JSON. The JSON library will generate valid JSON by escaping everything that needs to be escaped.

– JB Nizet
Nov 23 '18 at 14:29







It seems you're generating JSON by concatenating string parts. Don't do that. Use an actual JSON library to generate JSON nodes, or even better, to map objects to JSON. The JSON library will generate valid JSON by escaping everything that needs to be escaped.

– JB Nizet
Nov 23 '18 at 14:29















You are missing one final closing bracket in your first code snippet -- is that intentional? Because that's not a valid JSON text.

– amn
Nov 23 '18 at 14:38





You are missing one final closing bracket in your first code snippet -- is that intentional? Because that's not a valid JSON text.

– amn
Nov 23 '18 at 14:38












2 Answers
2






active

oldest

votes


















1














As pointed out in the comments, JSON does not allow control characters in strings. In the case of line breaks, these were encoded as n in the example.



You should definitely consider using a proper library to create the JSON rather than handling the raw strings yourself.






share|improve this answer































    0















    1. Create a POJO which will represent your gist (i.e. object with fields like 'description', 'files' collection. And separate POJO for file containing string fields 'name' and 'content';


    2. Do something like this to convert your gist:



      try {
      GistFile file new GistFile();// Assuming this is POJO for your file
      //Set name and content
      Gist gist = new Gist(); //Asuming this is a POJO for your gist
      gist.addFile(file);
      //Add more files if needed and set other properties
      ObjectMapper mapper = new ObjectMapper();
      String content = mapper.writeValueAsString(gist);
      //Now you have valid JSON string
      } catch (Exception e) {
      e.printStackTrace();
      }



    This is for com.fasterxml.jackson.databind.ObjectMapper or use different JSON library




    1. Actually there are GitHub specific libraries which do most of the job for you. Please refer to this question: How to connect to github using Java Program it might be helpful






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53448452%2fhow-to-convert-a-file-to-a-string-which-is-accepted-in-json%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      As pointed out in the comments, JSON does not allow control characters in strings. In the case of line breaks, these were encoded as n in the example.



      You should definitely consider using a proper library to create the JSON rather than handling the raw strings yourself.






      share|improve this answer




























        1














        As pointed out in the comments, JSON does not allow control characters in strings. In the case of line breaks, these were encoded as n in the example.



        You should definitely consider using a proper library to create the JSON rather than handling the raw strings yourself.






        share|improve this answer


























          1












          1








          1







          As pointed out in the comments, JSON does not allow control characters in strings. In the case of line breaks, these were encoded as n in the example.



          You should definitely consider using a proper library to create the JSON rather than handling the raw strings yourself.






          share|improve this answer













          As pointed out in the comments, JSON does not allow control characters in strings. In the case of line breaks, these were encoded as n in the example.



          You should definitely consider using a proper library to create the JSON rather than handling the raw strings yourself.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 14:44









          andyandy

          1,9331718




          1,9331718

























              0















              1. Create a POJO which will represent your gist (i.e. object with fields like 'description', 'files' collection. And separate POJO for file containing string fields 'name' and 'content';


              2. Do something like this to convert your gist:



                try {
                GistFile file new GistFile();// Assuming this is POJO for your file
                //Set name and content
                Gist gist = new Gist(); //Asuming this is a POJO for your gist
                gist.addFile(file);
                //Add more files if needed and set other properties
                ObjectMapper mapper = new ObjectMapper();
                String content = mapper.writeValueAsString(gist);
                //Now you have valid JSON string
                } catch (Exception e) {
                e.printStackTrace();
                }



              This is for com.fasterxml.jackson.databind.ObjectMapper or use different JSON library




              1. Actually there are GitHub specific libraries which do most of the job for you. Please refer to this question: How to connect to github using Java Program it might be helpful






              share|improve this answer






























                0















                1. Create a POJO which will represent your gist (i.e. object with fields like 'description', 'files' collection. And separate POJO for file containing string fields 'name' and 'content';


                2. Do something like this to convert your gist:



                  try {
                  GistFile file new GistFile();// Assuming this is POJO for your file
                  //Set name and content
                  Gist gist = new Gist(); //Asuming this is a POJO for your gist
                  gist.addFile(file);
                  //Add more files if needed and set other properties
                  ObjectMapper mapper = new ObjectMapper();
                  String content = mapper.writeValueAsString(gist);
                  //Now you have valid JSON string
                  } catch (Exception e) {
                  e.printStackTrace();
                  }



                This is for com.fasterxml.jackson.databind.ObjectMapper or use different JSON library




                1. Actually there are GitHub specific libraries which do most of the job for you. Please refer to this question: How to connect to github using Java Program it might be helpful






                share|improve this answer




























                  0












                  0








                  0








                  1. Create a POJO which will represent your gist (i.e. object with fields like 'description', 'files' collection. And separate POJO for file containing string fields 'name' and 'content';


                  2. Do something like this to convert your gist:



                    try {
                    GistFile file new GistFile();// Assuming this is POJO for your file
                    //Set name and content
                    Gist gist = new Gist(); //Asuming this is a POJO for your gist
                    gist.addFile(file);
                    //Add more files if needed and set other properties
                    ObjectMapper mapper = new ObjectMapper();
                    String content = mapper.writeValueAsString(gist);
                    //Now you have valid JSON string
                    } catch (Exception e) {
                    e.printStackTrace();
                    }



                  This is for com.fasterxml.jackson.databind.ObjectMapper or use different JSON library




                  1. Actually there are GitHub specific libraries which do most of the job for you. Please refer to this question: How to connect to github using Java Program it might be helpful






                  share|improve this answer
















                  1. Create a POJO which will represent your gist (i.e. object with fields like 'description', 'files' collection. And separate POJO for file containing string fields 'name' and 'content';


                  2. Do something like this to convert your gist:



                    try {
                    GistFile file new GistFile();// Assuming this is POJO for your file
                    //Set name and content
                    Gist gist = new Gist(); //Asuming this is a POJO for your gist
                    gist.addFile(file);
                    //Add more files if needed and set other properties
                    ObjectMapper mapper = new ObjectMapper();
                    String content = mapper.writeValueAsString(gist);
                    //Now you have valid JSON string
                    } catch (Exception e) {
                    e.printStackTrace();
                    }



                  This is for com.fasterxml.jackson.databind.ObjectMapper or use different JSON library




                  1. Actually there are GitHub specific libraries which do most of the job for you. Please refer to this question: How to connect to github using Java Program it might be helpful







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 23 '18 at 15:01

























                  answered Nov 23 '18 at 14:55









                  AkceptorAkceptor

                  1,40911524




                  1,40911524






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53448452%2fhow-to-convert-a-file-to-a-string-which-is-accepted-in-json%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      TypeError: fit_transform() missing 1 required positional argument: 'X'