String to Json - CSharp System.Runtime.Serialization.Json

CSharp examples for System.Runtime.Serialization.Json:Json

Description

String to Json

Demo Code


using System.Data.Common;
using System.Collections;
using System.Reflection;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System;//from ww  w . jav a2s  .  c o m

public class Main{

        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }
}

Related Tutorials