21 July 2013


如何将数组转化为 json 串?
下面的例子中我们示例如何将一个数据转换成 json 串,并使用 Gson.toJson() 方法将数组序列化为 JSON,以及Gson.fromJson() 方法将 JSON 串反序列化为 java 数组。
复制代码
import com.google.gson.Gson;

public class ArrayToJson {
    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 5, 8, 13};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

        //
        // Create a new instance of Gson
        //
        Gson gson = new Gson();

        //
        // Convert numbers array into JSON string.
        //
        String numbersJson = gson.toJson(numbers);

        //
        // Convert strings array into JSON string
        //
        String daysJson = gson.toJson(days);
        System.out.println("numbersJson = " + numbersJson);
        System.out.println("daysJson = " + daysJson);

        //
        // Convert from JSON string to a primitive array of int.
        //
        int[] fibonacci = gson.fromJson(numbersJson, int[].class);
        for (int i = 0; i < fibonacci.length; i++) {
            System.out.print(fibonacci[i] + " ");
        }
        System.out.println("");

        //
        // Convert from JSON string to a string array.
        //
        String[] weekDays = gson.fromJson(daysJson, String[].class);
        for (int i = 0; i < weekDays.length; i++) {
            System.out.print(weekDays[i] + " ");
        }
        System.out.println("");

        //
        // Converting multidimensional array into JSON
        //
        int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
        String json = gson.toJson(data);
        System.out.println("Data = " + json);

        //
        // Convert JSON string into multidimensional array of int.
        //
        int[][] dataMap = gson.fromJson(json, int[][].class);
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                System.out.print(data[i][j] + " ");
            }
            System.out.println("");
        }
    }
}
复制代码
以下是输出结果:
复制代码
numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13 
Sun Mon Tue Wed Thu Fri Sat 
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3 
3 4 5
复制代码

如何将集合转化为 json 串?
下面的例子中我们示例如何将Java集合转换为符合 json 规则的字符串。
复制代码
import java.util.Date;

public class Student {
    private String name;
    private String address;
    private Date dateOfBirth;

    public Student() {
    }

    public Student(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
}
复制代码
复制代码
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CollectionToJson {
    public static void main(String[] args) {
        //
        // Converts a collection of string object into JSON string.
        //
        List<String> names = new ArrayList<String>();
        names.add("Alice");
        names.add("Bob");
        names.add("Carol");
        names.add("Mallory");

        Gson gson = new Gson();
        String jsonNames = gson.toJson(names);
        System.out.println("jsonNames = " + jsonNames);

        //
        // Converts a collection Student object into JSON string
        //
        Student a = new Student("Alice", "Apple St", new Date(2000, 10, 1));
        Student b = new Student("Bob", "Banana St", null);
        Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21));
        Student d = new Student("Mallory", "Mango St", null);

        List<Student> students = new ArrayList<Student>();
        students.add(a);
        students.add(b);
        students.add(c);
        students.add(d);

        gson = new Gson();
        String jsonStudents = gson.toJson(students);
        System.out.println("jsonStudents = " + jsonStudents);

        //
        // Converts JSON string into a collection of Student object.
        //
        Type type = new TypeToken<List<Student>>(){}.getType();
        List<Student> studentList = gson.fromJson(jsonStudents, type);

        for (Student student : studentList) {
            System.out.println("student.getName() = " + student.getName());
        }
    }
}
复制代码
以下是输出结果:
复制代码
jsonNames = ["Alice","Bob","Carol","Mallory"]
jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory
复制代码

如何将Map转化为 json 串?
下面的例子中我们示例如何将java.util.Map转化成 json 串,然后再将 json 串转换为java.util.Map。
复制代码
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class MapToJson {
    public static void main(String[] args) {
        Map<String, String> colours = new HashMap<String, String>();
        colours.put("BLACK", "#000000");
        colours.put("RED", "#FF0000");
        colours.put("GREEN", "#008000");
        colours.put("BLUE", "#0000FF");
        colours.put("YELLOW", "#FFFF00");
        colours.put("WHITE", "#FFFFFF");

        //
        // Convert a Map into JSON string.
        //
        Gson gson = new Gson();
        String json = gson.toJson(colours);
        System.out.println("json = " + json);

        //
        // Convert JSON string back to Map.
        //
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> map = gson.fromJson(json, type);
        for (String key : map.keySet()) {
            System.out.println("map.get = " + map.get(key));
        }
    }
}
复制代码
以下是输出结果:
复制代码
json = {"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}
map.get = #FFFFFF
map.get = #0000FF
map.get = #FFFF00
map.get = #008000
map.get = #000000
map.get = #FF0000
复制代码

如何将对象转换为 json 串?
下面的例子中我们示例如何将一个 Student 对象转换成 json 串,实际操作中我们也可以将任意的 Java 类转换为 json 串,并且实施起来也非常简单,你仅仅需要创建一个 Gson 实例,然后传递将被转化为 json 串的对象,并调用该实例的 toJson 方法即可。
复制代码
import com.google.gson.Gson;

import java.util.Calendar;

public class StudentToJson {
    public static void main(String[] args) {
        Calendar dob = Calendar.getInstance();
        dob.set(2000, 1, 1, 0, 0, 0);
        Student student = new Student("Duke", "Menlo Park", dob.getTime());

        Gson gson = new Gson();
        String json = gson.toJson(student);
        System.out.println("json = " + json);
    }
}
复制代码
复制代码
import java.util.Date;

public class Student {
    private String name;
    private String address;
    private Date dateOfBirth;

    public Student() {
    }

    public Student(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
}
复制代码
以下是输出结果:
json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}

如何将 json 串转换为对象?
下面的例子中我们示例如何 json 串转化成 Java对象。
复制代码
import com.google.gson.Gson;

public class JsonToStudent {
    public static void main(String[] args) {
        String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}";

        Gson gson = new Gson();
        Student student = gson.fromJson(json, Student.class);

        System.out.println("student.getName()        = " + student.getName());
        System.out.println("student.getAddress()     = " + student.getAddress());
        System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth());
    }
}
复制代码
以下是输出结果:
student.getName()        = Duke
student.getAddress()     = Menlo Park
student.getDateOfBirth() = Tue Feb 01 00:00:00 CST 2000

如何处理对象的字段?
下面的例子中我们示例如何利用Gson处理一个对象的某一字段。
复制代码
import com.google.gson.Gson;

import java.util.Calendar;

public class GsonFieldExample {
    public static void main(String[] args) {
        Calendar dob = Calendar.getInstance();
        dob.set(1980, 10, 11);
        People people = new People("John", "350 Banana St.", dob.getTime());
        people.setSecret("This is a secret!");

        Gson gson = new Gson();
        String json = gson.toJson(people);
        System.out.println("json = " + json);
    }
}
复制代码
复制代码
import java.util.Date;

public class People {
    private String name;
    private String address;
    private Date dateOfBirth;
    private Integer age;
    private transient String secret;

    public People(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }
}
复制代码
 以下是输出结果:
json = {"name":"John","address":"350 Banana St.","dateOfBirth":"Nov 11, 1980 8:47:04 AM"}

17 July 2013

如果让莎士比亚、海明威编写JavaScript代码

如果让莎士比亚、海明威编写JavaScript代码

摘要:每位开发者都有自己习惯的编码风格,而文学作家也有自己标志性的写作方式。试想一下,如果让莎士比亚、海明威这样的大文豪来写JavaScript代码,会呈现出什么样的风格呢?
本文作者Angus Croll是Twitter工程师、JavaScript迷、文学迷,并且非常喜欢作家海明威。他在梦中"梦见"一些名人编写JavaScript代码,不同的作家呈现出各种编程风格,大家不妨一起来品尝下。
下面是对原文的摘译。
最近,我做了一个梦,我请海明威和其他四位文学名人替我编写JavaScript代码,一个函数返回一个给定长度的斐波纳契数列。有趣地是,他们每个人都以不同的方式完成了这一题,并且都做的很好——只是我想说,每个解决方案工作起来都好比广告(即使是Andre Breton的),后来我又请包括海明威在内的7名文豪用JavaScript来编写阶乘,似乎一切都那么神奇,但他们都成功地完成了,大家不妨来看看结果吧。
一、实现斐波纳契数列
1.欧内斯特·海明威(Ernest Hemingway 美国作家) 
代表作:《老人与海》《太阳照样升起》《永别了,武器》《丧钟为谁而鸣》
1
2
3
4
5
6
7
8
9
10
11
12
function fibonacci(size) {
  var first = 0, second = 1, next, count = 2, result = [first, second];
  if(size < 2)
    return "the request was made but it was not good"
  while(count++ < size) {
    next = first + second;
    first = second;
    second = next;
    result.push(next);
  }
  return result;
}
简洁明了的代码,没有任何多余的字母和变量,没有精心设计的逻辑和聪明的变量命名,非常平淡地表明了它是做什么的,仅此而已,这就是海明威的魅力之处。
2.威廉·莎士比亚(William Shakespeare 英国诗人、戏剧家)
代表作: 《哈姆雷特》《奥赛罗》《李尔王》《罗密欧与朱丽叶》等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function theSeriesOfFIBONACCI(theSize) {
  //a CALCKULATION in two acts.
  //employ'ng the humourous logick of JAVA-SCRIPTE
  //Dramatis Personae
  var theResult;//an ARRAY to contain THE NUMBERS
  var theCounter;//a NUMBER, serv'nt to the FOR LOOP
  //ACT I: in which a ZERO is added for INITIATION
  //[ENTER: theResult]
  //Upon the noble list bestow a zero
  var theResult = [0];
  //ACT II: a LOOP in which the final TWO NUMBERS are QUEREED and SUMM'D
  //[ENTER: theCounter]
  //Commence at one and venture o'er the numbers
  for (theCounter = 1; theCounter < theSize; theCounter++) {
    //By divination set adjoining members
    theResult[theCounter] = (theResult[theCounter-1]||1) + theResult[Math.max(0, theCounter-2)];
  }
  //'Tis done, and here's the answer.
  return theResult;
  //[Exuent]
}
大家可以看看莎士比亚是如何使用抑扬格五音步编写注释的。熟悉他戏剧的朋友应该对抑扬格五音步非常熟悉吧。
3.安德烈·布勒东(Andre Breton 法国诗人)
代表作:《超现实主义宣言》
1
2
3
4
5
6
7
8
9
function Colette(umbrella) {
  var staircase = 0, galleons = 0, brigantines = 1, armada = [galleons, brigantines], bassoon;
  Array.prototype.embrace = [].push;
  while(2 + staircase++ < umbrella) {
    bassoon = galleons + brigantines;
    armada.embrace(brigantines = (galleons = brigantines, bassoon));
  }
  return armada;
}
整个解决方案的逻辑非常清晰、优雅,在galleons、brigantines、bassoons这三个之间,使用逗号操作符对它们进行同时转移。
4.罗贝托·波拉尼奥(Roberto Bolano 智利小说家、诗人)
代表作:《荒野侦探》《2666》
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function LeonardoPisanoBigollo(l) {
  if(l < 0) {
    return "I'd prefer not to respond. (Although several replies occur to me)"
  }
  /**/
  //Everything is getting complicated.
  for (var i=2,r=[0,1].slice(0,l);i<l;r.push(r[i-1]+r[i-2]),i++)
  /**/
  //Here are some other mathematicians. Mostly it's just nonsense.
  rationalTheorists = ["Archimedes of Syracuse", "Pierre de Fermat (such margins, boys!)", "Srinivasa Ramanujan", "Rene Descartes", "Leonhard Euler", "Carl Gauss", "Johann Bernoulli", "Jacob Bernoulli", "Aryabhata", "Brahmagupta", "Bhaskara II", "Nilakantha Somayaji", "Omar Khayyám", "Muhammad ibn Mūsā al-Khwārizmī", "Bernhard Riemann", "Gottfried Leibniz", "Andrey Kolmogorov", "Euclid of Alexandria", "Jules Henri Poincaré", "Srinivasa Ramanujan", "Alexander Grothendieck (who could forget?)", "David Hilbert", "Alan Turing", "von Neumann", "Kurt Gödel", "Joseph-Louis Lagrange", "Georg Cantor", "William Rowan Hamilton", "Carl Jacobi", "Évariste Galois", "Nikolay Lobachevsky", "Rene Descartes", "Joseph Fourier", "Pierre-Simon Laplace", "Alonzo Church", "Nikolay Bogolyubov"]
  /**/
  //I didn't understand any of this, but here it is anyway.
  return r
  /**/
  //Nothing happens here and if it does I'd rather not talk about it.
}
长短不齐的段落,缺少分号,使用隐式全局变量——对每一个变量都做进一步深入的说明。
5. 查尔斯·狄更斯(Charles Dickens 英国小说家)
代表作:《匹克威克外传》《雾都孤儿》《 双城记 》等
1
2
3
4
5
6
7
8
9
10
function mrFibbowicksNumbers(enormity) {
  var assortment = [0,1,1], tally = 3, artfulRatio = 1.61803;
 
  while(tally++ < enormity) {
    //here is an exceedingly clever device
    assortment.push(Math.round(assortment[tally-2] * artfulRatio));
  }
  //should there be an overabundance of elements, a remedy need be applied
  return assortment.slice(0, enormity);
}
从代码中可以看出,他没有体会到斐波那契数列的基本理念,而是采用乘法解决。代码里也有些有趣的命名,但缺乏核心地理解。
二、实现factorial(n)阶乘 
以上是这些著名的作家用JavaScript编写斐波那契数列,下面再让我们看看,作家们是如何用JavaScript/CoffeeScript编写factorial(n)的。
1. 杰克·凯鲁亚克(Jack Kerouac 美国小说家)
代表作:《在路上》《贩毒者》等
1
2
3
4
5
6
7
/*...the only numbers for me are the mad ones, take forty-three like a
steam engine with a talky caboose at the end*/n = 43,/*and that lanky
fellow in a cocked fedora*/r = 1/*then back to our number, our mad
number, mad to become one*/while (n > 1)/*mad to descend*/n--,/*mad
to multiply*/r = r * n/*and at the end, you see the blue center-light
pop, and everybody goes 1.4050061177528801e+51...*/
r
上面代码只能返回43的阶乘,如果想要实现另一个数的阶乘,你还需重写代码。不过,最值得注意地是,注释和代码几乎没有区别,无法分辨,从侧面反映了Kerouac的风格,很长、狂野和狂想式的流露。
2.塞缪尔·约翰逊(Samuel Johnson 英国作家、诗人)
代表作:《英语大辞典》《伦敦》《人类欲望的虚幻》等
1
2
3
4
5
6
7
8
9
10
11
# In which various NUMBERS are summon'd by
# means of ELECTRONICK CONJURY
factorial = (n) ->
   # All argument is against it; yet all belief is for it
   return 1 unless n
   # Ingenious sophistry to prove the palp'bly OBVIOUS
   return 1 if n is 1
   # Recursion (n.)
   # a program that calls 'pon itself in the manner of
   # a dog returning unto its VOMIT
   return n * factorial n - 1
整段代码比较稀疏,中间也掺杂着Johnson的精言妙语:其中,他也对factorial(0)应该为1进行了怀疑,他应该用一个完整的句子来表达factorial(1)就是1,从其字典里进行推测,完成了一个具有讽刺定义的递归解除。
Johnson的整个解决方案充满着艺术和模仿的结合——带有整洁表达式地温和的自我嘲讽和真正美丽的混合。
3.詹姆斯·乔伊斯(James Joyce 爱尔兰作家、诗人)
代表作:《尤利西斯》
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function hacktorial(integette) {
  var nonthings = [undefined, null, false, 0, '', NaN];
  var resultution = 1;
 
  if (integette == 0) {
    //behold the strangerous zeroine!
    resultution = 1;
  } else {
    while (integette > 1)
    //caligulate by multicapables
    resultution = resultution * integette--;
  }
  with(resultution) {
    var duodismal =  Function('return this').call(toString(12));
    var disemvowel = Function("n","return n?parseInt(n,12):'0'")
    return [
      disemvowel(duodismal.slice(0,-1)),
      'shillings and',
      disemvowel(duodismal[duodismal.length-1]), 'pence'
    ].join(' ');
  }
  //klikkaklakkaklaskaklopatzklatschabattacreppycrottygraddahappluddyappladdypkonpkot!
}
Joyce不仅仅是解决了阶乘问题,前半部分代码已经解决了这个问题,但Joyce坚决把结果转换为当时的货币:先令和便士。
结果:
1
2
3
4
hacktorial(3)//"0 shillings and 6 pence"
hacktorial(4)//"2 shillings and 0 pence"
hacktorial(7)//"420 shillings and 0 pence"
hacktorial(21)//"4257578514309120000 shillings and 0 pence"
4.理查德·费曼(Richard Feynman美国物理学家)
代表作:《费曼物理学讲义》《物理之美》
1
2
3
4
5
6
7
8
//using Ramanujan's approximation
function fractorail(n){
  with(Math) {
    var r = sqrt(PI)*pow(n/E,n);
    r *= pow(8*pow(n, 3) + 4*(n*n) + n + 1/30, 1/6);
    return r;
  }
}
费曼的工作的特点是具有大胆的创意和非常古怪的才华,从它所编写的这段代码中也能看出。
结果,不要担心一些“舍入误差”,如果你非常熟悉JavaScript,你就应该知道:
1
2
3
fractorail(3);//6.00005
fractorail(1.1);//1.04671
fractorail(5.2);//169.40628
5. 阿瑟·柯南·道尔(Arthur Conan Doyle世界著名小说家)
代表作:《福尔摩斯探案集》《失落的世界》
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"use strict";
//In solving a problem of this sort, the grand thing is to be able to reason backwards...
//some things are easier known than explained!
var caseHistory = new Object({2:2, 6:3});
function unfactorial(evidence){
    //first, humility!
    if (evidence === 1) {
      return "Watson, I am at a loss!"
    }
    //second, logical precedence!
    if(caseHistory[evidence]){
      //elementary!
      return caseHistory[evidence];
    }
    //third, eliminate the impossible!
    if(evidence === 0 || evidence % 24 !== 0) {
      return "charlatans!";
    }
    //fourth, deduction!
    var theDeduction, enumarator = evidence, denominator = 1;
    while(enumarator % denominator === 0) {
      enumarator = enumarator/denominator++;
      if (enumarator === denominator) {
        theDeduction = enumarator;
      }
    }
    theDeduction = theDeduction || "impostors";
    //What one man can invent another can discover!
    caseHistory[evidence] = theDeduction;
    //What remains, however improbable, must be the truth!
    return theDeduction;
}
正如大家想象的那样, 柯南道尔的设计过程是精确和认真有序的,此外,大家可能注意到,他让其应用程序在strict模式运行——容不得半点马虎。
6.简·奥斯汀(Jane Austen 英国小说家)
代表作:《理智与情感》 《傲慢与偏见》
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
factorial = (function() {
  //I declare...
  var ledger = {};
  return function reckoning(quantity) {
    if (isNaN(quantity)) {
      console.log("I have not the pleasure of understanding you");
      return;
    }
    //It is a truth universally acknowledged that two values
    //can only be adjudged truly agreeable by means of ===
    if (quantity === 0) {
      return 1;
    }
    //Mr Crockford teaches that we be wary of inherited property...
    if (ledger.hasOwnProperty(quantity)) {
      return ledger[quantity];
    }
    //Pray persist until an answer is furnished
    return ledger[quantity] = quantity * reckoning(quantity - 1);
  };
})();
Jane Austen解决方案的亮点之一是代码工艺和结构的完整性,主要体现在代码块的整洁上,她调用模块模式,隐藏历史数据(或ledger)在上层结构的文件夹里;第二个则是体现了Jane Austen的俏皮,甚至是颠覆性的,对power的讽刺和荒谬的约定。
7. 欧内斯特·海明威(Ernest Hemingway 美国小说家)
代表作:《老人与海》《太阳照样升起》等
1
2
3
4
//Economy.
function factorial(n) {
  return n < 2 ? 1: factorial(n-1)*n;
}
代码足以说明一切。
我们从中所学到的
这些著名的小说家、诗人、戏剧家的伟大之处在于他们勇于开拓新方式,尝试新的技术并且打破我们一直所遵循的规律。
最优秀的英语作家具有着对规则的蔑视。——Steven Pinker
JavaScript作为最流行的编程语言之一,它的进步取决于开发者们地大胆创新、研究以及发现新模式,这样才能惠及更多的人。
各位开发者们,如果让你们喜欢的作家来编写JavaScript代码会是啥样呢?不妨一起探讨下吧。