0

I created a model class (only show constructor here)

public PieceModel(int position, int piece_id) {
    this.position = position;
    this.piece_id = piece_id;
}

then add some data

list.add(new PieceModel(1, 100));
list.add(new PieceModel(2, 300));
list.add(new PieceModel(3, 600));

and then i convert list to string and it print like this

[{"piece_id":100,"position":1},{"piece_id":300,"position":2},{"piece_id":600,"position":3}]

but i need it like this

[{"position":1,"piece_id":100},{"position":2,"piece_id":200},{"position":3,"piece_id":300}]

some advice please..

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
J.D
  • 58
  • 6
  • 2
    Read up how to sort a list by using `Comparator`. [This](https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) will help. Come back after you have read it up and if you're not able to implement it properly. – Nicholas K Dec 31 '18 at 09:46
  • @Nicholas K I don't think he is talking about sorting. He just wants the properties to appear in the way he sets. – KiraAG Dec 31 '18 at 09:51
  • Does the property order matters, as you are still going to access it with names ? – KiraAG Dec 31 '18 at 09:52
  • @KiraAG: See the tags OP has used. It clearly says *sorting*. – Nicholas K Dec 31 '18 at 09:53
  • @Nicholas K Ya I saw that, But the OP's ask states otherwise. I ll let the OP decide what he wants. Anyway thanks for referencing the link, I learnt something new. – KiraAG Dec 31 '18 at 09:56
  • yes i need property order to appear in the way i set, because i am trying to match that string with another string – J.D Dec 31 '18 at 09:57
  • Then you need to clearly implement the sorting the way @Nicholas K mentioned – KiraAG Dec 31 '18 at 10:00
  • What code do you use to "convert to `String`"? That's where the issue lies and that's where you need to solve it. Please show the code you use to convert `PieceModel` to `String`. – David Wasser Dec 31 '18 at 12:44

1 Answers1

4

Something like this? Override toString and re-arrange the properties?

static class PieceModel {
    private int position;
    private int piece_id;

    public PieceModel(int position, int piece_id) {
        this.position = position;
        this.piece_id = piece_id;
    }

    @Override
    public String toString() {
        return "{" +
                "position=" + position +
                ", piece_id=" + piece_id +
                '}';
    }
}

public static void main(String[] args) {
    List<PieceModel> list = new ArrayList<>();
    list.add(new PieceModel(1, 100));
    list.add(new PieceModel(2, 300));
    list.add(new PieceModel(3, 600));
    System.out.print(list.toString());
}

Result:

[{"position":1,"piece_id":100},{"position":2,"piece_id":200},{"position":3,"piece_id":300}]
phatnhse
  • 3,870
  • 2
  • 20
  • 29