猿问

从服务器上的响应返回后,如何将这些值设置为 List<Models>?

我正在研究从服务器响应值的 Http API。我的问题是响应发送字符串值就像没有 JSON 对象一样。


Username:password:level

user1:user1:2

user2:user2:2

user3:user3:2

user4:user4:2

没有其他的。所以,


List<Models> model;

List<String> stringList = new ArrayList<>;

String[] couple=response.split(":");

for (int i = 3; i < couple.length - 1; i++) {

     items = couple[i].split("\n");

     String models = gson.toJson(items[0]);

     Log.d(TAG, "a is ----> \t" + models);

     stringList.add(models);


}

model = (List)stringList;

logcat 显示如下内容:


  a is  ---->   user1

  a is  ---->   2

  a is  ---->   user2

  a is  ---->   2

模型类是:


public class Models{

    private static final String TAG = Models.class.getName();


    private String mUserName;

    private String mPassword;

    private int mlevel;


    public Models(){


    }


    public String getmUserName() {

        return mUserName;

    }


    public void setmUserName(String mUserName) {

        this.mUserName = mUserName;

    }


    public String getmPassword() {

        return mPassword;

    }


    public void setmPassword(String mPassword) {

        this.mPassword = mPassword;

    }


    public int getMlevel() {

        return mlevel;

    }


    public void setMlevel(int mlevel) {

        this.mlevel = mlevel;

    }

我不知道该如何处理。


慕盖茨4494581
浏览 135回答 2
2回答

jeck猫

您可以使用split()自己来解析字符串:List<Models> models = new ArrayList<>();String[] lines = result.split("\n");for (String line : lines) {&nbsp; &nbsp; String[] items = line.split(":");&nbsp; &nbsp; Model model = new Models();&nbsp; &nbsp; model.setmUserName(items[0]);&nbsp; &nbsp; model.setmPassword(items[1]);&nbsp; &nbsp; model.setMlevel(Integer.valueOf(items[2]);&nbsp; &nbsp; models.add(model);}关于名字的一句话:Models应该重命名,User因为这更准确地描述了模型所代表的内容。去掉m成员变量的前缀和m所有访问器中的 。例如,访问器应该命名为getPassword()and setPassword(),而不是getmPasword()and setmPassword()。

qq_花开花谢_0

可能你应该先用“\n”分割得到每一行,然后用“:”分割得到每个coloum,像这样&nbsp; &nbsp; String[] couple = result.split("\n");&nbsp; &nbsp; for (int i = 1; i < couple.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; String[] items = couple[i].split(":");&nbsp; &nbsp; &nbsp; &nbsp; Log.e("Look Here:", "a is ----> \t" + items[0] + "," + items[1] + ","&nbsp; + items[2]);&nbsp; &nbsp; }希望有用
随时随地看视频慕课网APP

相关分类

Java
我要回答