0

我想检查从 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);
        }
    }
}

这是我的枚举类

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

这是返回的标签...

“标签”:[“泰迪熊”,“室内”,“衣服”,“领带”,“人”,“熊”,“穿着”,“绿色”,“棕色”,“填充”,“坐着”,男人“,弓”,“脖子”,“脸”,“衬衫”,“蓝色”,“帽子”,“关闭”,“灰色”,“铺设”,“黑色”,“眼镜”,“头” ,"床","白色","抱着","猫","睡觉"]}

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

4

1 回答 1

0

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

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);
    }
}

你的枚举是这样的:

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;
    }
}
于 2018-04-01T13:29:28.683 回答