Firebase数据排序与接收问题:字段拆分失败、排序失效
I’ve run into both of these exact headaches before, so let’s break them down and fix them step by step:
1. Extracting name and score from the JSON String
Manually picking apart JSON strings is error-prone—instead, use a JSON serialization library to map the string directly to your data class. Here are the two most common approaches:
Option 1: Use Jackson (standard for Java apps)
First, make sure your data class matches the JSON structure:
public class DataRecord { private String name; private int score; // Use Integer if score can be null // Required no-arg constructor, plus getters and setters public DataRecord() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } }
Then parse the JSON string into your class:
import com.fasterxml.jackson.databind.ObjectMapper; // Reuse this ObjectMapper instance across your code ObjectMapper objectMapper = new ObjectMapper(); String jsonResponse = key.getValue().toString(); // Map JSON directly to your data class DataRecord record = objectMapper.readValue(jsonResponse, DataRecord.class); // Now access fields directly String userName = record.getName(); int userScore = record.getScore();
Option 2: Quick Manual Parsing (no libraries needed)
If you prefer a lightweight approach, use the built-in JSONObject class:
import org.json.JSONObject; String jsonResponse = key.getValue().toString(); JSONObject jsonObj = new JSONObject(jsonResponse); String userName = jsonObj.getString("name"); int userScore = jsonObj.getInt("score");
Note: This works for simple JSON, but libraries are better for complex/nested data structures.
2. Fixing Sorting & Missing Data Problems
The fallback to date sorting and eventual empty results points to a few common pitfalls—let’s troubleshoot:
Double-check your sort configuration: Did you accidentally type
dateinstead ofscorein your sort rule? For example, with JPA:// Wrong: Sorts by date instead of score Sort incorrectSort = Sort.by("date"); // Correct: Sorts by score (ascending or descending) Sort correctSort = Sort.by(Sort.Direction.DESC, "score"); List<DataRecord> sortedRecords = dataRepository.findAll(correctSort);Check the
scorefield type: Ifscoreis stored as a string (not a numeric type), sorting will use lexicographical order (e.g., "100" comes before "90") instead of numeric order. Fix this by:- Changing the field type to
int/longin your database and data class, or - Adding a custom comparator in code:
List<DataRecord> records = dataRepository.findAll(); // Sort by numeric value even if score is stored as string records.sort(Comparator.comparingInt(record -> Integer.parseInt(record.getScore())));
- Changing the field type to
Verify query filters: If no records return, check for unintended filters. For example:
- Are you excluding records where
scoreis null? If all records have null scores, this would return nothing. - Is pagination set incorrectly (e.g., requesting page 5 when only 2 pages exist)?
- Are you excluding records where
Log the actual query: Enable SQL logging to see what’s being executed against your database. You’ll instantly spot if the sort clause is wrong, or if a WHERE condition is filtering out all data.
Final Tip
Start by confirming you can correctly extract name and score from a single JSON string first—once that’s solid, debug the sorting issue using the actual data you’re retrieving.
内容的提问来源于stack exchange,提问作者John Spring

