如何检查枚举类中的值?

时间:2018-04-01 11:51:07

标签: java android json enum-class

我想检查从json对象返回的标签是否具有枚举类中的一个值。

Gson gson = new Gson();
            AnalysisResult result = gson.fromJson(data, AnalysisResult.class);
for(Enum p : Enum.values()){
    if(p.name().equals(result.tags)){
        Intent in1 = new Intent(Analyze.this,  Analyze2.class);
        startActivity(in1);
    }else {
        for (final Caption caption : result.description.captions) {
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    speakOut("Result:" + caption.text);  
                }
            }, 100);
        }
    }
}

这是我的Enum课程

public enum Enum {
    person,
    people,
    people_baby,
    people_crowd,
    people_group,
    people_hand,
    people_many,
    people_portrait,
    people_show,
    people_tattoo,
    people_young
}

这是返回的标签......

  

“标签”: “泰迪熊”, “室内”, “服装”, “领带”, “人”, “熊”, “穿”, “绿色”, “棕色”, “酿”,“坐”, “人”, “弓”, “脖子”, “面子”, “衬衫”, “蓝”, “帽子”, “关闭”, “灰色”, “铺”, “黑”, “眼镜”, “头”, “床”, “白”, “保持”, “猫”, “睡眠”]}

我的问题是它总是转到else语句。您认为代码有什么问题?

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解你想要在这里实现的目标,而且我不知道这是什么' Tag'对象,但我想你想做这样的事情:

Gson gson = new Gson();
AnalysisResult result = gson.fromJson(data, AnalysisResult.class);
boolean hasTag = false;
for (Tag t : result.tags) {
    if (Enum.hasTag(t.getTagName())) {
        hasTag = true;
        break;
    }
}

if (hasTag) {
    Intent in1 = new Intent(Analyze.this, Analyze2.class);
    startActivity(in1);
} else {
    for (final Caption caption : result.description.captions) {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                speakOut("Result:" + caption.text);
            }
        }, 100);
    }
}

你的Enum是这样的:

public enum Enum {
    person,
    people,
    people_baby,
    people_crowd,
    people_group,
    people_hand,
    people_many,
    people_portrait,
    people_show,
    people_tattoo,
    people_young;

    public static boolean hasTag(String tag) {
        for (Enum e : values()) {
            if (e.name().equals(tag))
                return true;
        }

        return false;
    }
}