冒泡存储在JSONArray中的Java字符串排序

时间:2014-06-14 17:07:44

标签: java json sorting bubble-sort

我在磁盘上保存了一个JSON文件,如下所示:

{
  "author": [
    "Mario Vargas Llosa",
    "Maria Duenas",
    "Liviu Rebreanu",
    "Liviu Rebreanu"
  ],
  "nameBook": [
    "Eroul discret",
    "Iubirile croitoresei",
    "Ion",
    "Ion"
  ],
  "priceBook": [
    34,
    28,
    40,
    40
  ],
  "publisherBook": [
    "Humanitas",
    "Polirom",
    "Humanitas",
    "Dacia"
  ],
  "idBook": [
    1,
    2,
    3,
    4
  ]
}

然后我有以下Java代码:

// read the json file
FileReader reader = new FileReader(filePath);

JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

// get a String from the JSON object

JSONArray idBookJ =  (JSONArray) jsonObject.get("idBook");
JSONArray nameBookJ = (JSONArray) jsonObject.get("nameBook");
JSONArray authorJ = (JSONArray) jsonObject.get("author");
JSONArray publisherBookJ = (JSONArray) jsonObject.get("publisherBook");
JSONArray priceBookJ = (JSONArray) jsonObject.get("priceBook");

现在,我需要使用冒泡排序,在单词的第一个字母后按字母顺序对publisherBook标记中的内容进行排序。我知道这不是最令人惊讶的编程挑战,但我仍然坚持将JSONArray中的字符串视为......字符串。

2 个答案:

答案 0 :(得分:1)

这应该让你开始,

static class Book {
  public Book() {

  }
  int id;
  String name;
  String author;
  String publisher;
  int price;
  public String toString() {
    return "[" + id + " " + name + " " + author + " " + publisher + " " + price + "]";
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getAuthor() {
    return author;
  }
  public void setAuthor(String author) {
    this.author = author;
  }
  public String getPublisher() {
    return publisher;
  }
  public void setPublisher(String publisher) {
    this.publisher = publisher;
  }
  public int getPrice() {
    return price;
  }
  public void setPrice(int price) {
    this.price = price;
  } 
}

public static void main(String[] args) {
  // read the json file
  FileReader reader = new FileReader(filePath);

  JSONParser jsonParser = new JSONParser();
  JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

  // get a String from the JSON object

  JSONArray idBookJ =  (JSONArray) jsonObject.get("idBook");
  JSONArray nameBookJ = (JSONArray) jsonObject.get("nameBook");
  JSONArray authorJ = (JSONArray) jsonObject.get("author");
  JSONArray publisherBookJ = (JSONArray) jsonObject.get("publisherBook");
  JSONArray priceBookJ = (JSONArray) jsonObject.get("priceBook");
  Book[] books = new Book[idBookJ.size()]; 
  for (int i = 0; i < idBookJ.size(); i++) {
    books[i] = new Book();
    books[i].setId(idBookJ.getInt(i));
    books[i].setName(nameBookJ.getString(i));
    books[i].setAuthor(authorJ.getString(i));
    books[i].setPublisher(publisherBookJ.getString(i));
    books[i].setPrice(priceBookJ.getInt(i));
  }
  Comparator<Book> publisherComparator = new Comparator<Book>() {
    @Override
    public int compare(Book o1, Book o2) {
      return o1.getPublisher().compareTo(o2.getPublisher());
    }
  };
  // Now your Books are in the book[], and you have a Comparator that can compare them by
  // publisher.
}

答案 1 :(得分:0)

solution对我有用,但我仍然会发布代码以防万一。它不是纯粹的冒泡排序,但它比几乎没有更好。

JSON数组:

[
   {
      "firstName":"John",
      "lastName":"Doe"
   },
   {
      "firstName":"Anna",
      "lastName":"Smith"
   },
   {
      "firstName":"Peter",
      "lastName":"Jones"
   }
]

JSON Simple库可用here

package com.iglooworks.test;
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;

    import java.util.Set;
    import java.util.SortedMap;
    import java.util.TreeMap;

    public class JsonSorter {
        public static JSONArray sortJsonByKey(JSONArray json, String key)
        {
            JSONArray sorted = new JSONArray();
            SortedMap map = new TreeMap();

            for (Object o : json) {
                JSONObject tmp = (JSONObject) o;
                map.put(tmp.get(key),tmp);
            }

            Set<String> numbers = map.keySet();

            for (String number : numbers) {
                sorted.add(map.get(number));
            }

            return sorted;
        }

}

用法似乎非常简单:

package com.iglooworks.test;

import com.iglooworks.tools.JsonSorter;
import org.json.simple.*;

public class Test {
    public static void main(String[] args) {
                String json = "[\n" +
                "   {\n" +
                "      \"firstName\":\"John\",\n" +
                "      \"lastName\":\"Doe\"\n" +
                "   },\n" +
                "   {\n" +
                "      \"firstName\":\"Anna\",\n" +
                "      \"lastName\":\"Smith\"\n" +
                "   },\n" +
                "   {\n" +
                "      \"firstName\":\"Peter\",\n" +
                "      \"lastName\":\"Jones\"\n" +
                "   }\n" +
                "]";

        JSONArray jsonArray;
        try {
            jsonArray = tools.sortJsonByKey((JSONArray) JSONValue.parse(json), "firstName");


            for (Object o : jsonArray) {
                JSONObject tmp = (JSONObject) o;
                System.out.println(tmp.get("firstName") + " - " + tmp.get("lastName"));
            }

        } catch (Exception e) {
            e.printStackTrace(); 
        }


    }
}

最后的想法:我发现这个解决方案可能导致NullPointerException,所以当我有时间的时候我会尝试改进它。