将3个JSON对象反序列化为一个Java对象,使用Gson。

huangapple go评论75阅读模式
英文:

Deserialize 3 json objects to one java object with Gson

问题

你可以尝试修改你的Java类和反序列化代码,以正确处理JSON对象并创建一个Java对象。这是修改后的代码示例:

public class Item {
    double from1To2;
    double from3To4;
    double from5To6;

    public Item(double from1To2, double from3To4, double from5To6) {
        this.from1To2 = from1To2;
        this.from3To4 = from3To4;
        this.from5To6 = from5To6;
    }

    @Override
    public String toString() {
        return "from 1 to 2: " + from1To2 + "\nfrom 3 to 4: " + from3To4 + "\nfrom 5 to 6: " + from5To6;
    }
}

public class ItemDeserializer implements JsonDeserializer<Item> {
    @Override
    public Item deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        double value = Double.parseDouble(jsonObject.get("value").getAsString());

        int from = Integer.parseInt(jsonObject.get("from").getAsString());
        int to = Integer.parseInt(jsonObject.get("to").getAsString());

        double fromToValue = (from == 1 && to == 2) ? value : 0;
        double from3To4Value = (from == 3 && to == 4) ? value : 0;
        double from5To6Value = (from == 5 && to == 6) ? value : 0;

        return new Item(fromToValue, from3To4Value, from5To6Value);
    }
}

// 在你的主代码中:
Gson gson = new GsonBuilder()
    .registerTypeAdapter(Item.class, new ItemDeserializer())
    .create();

Type itemsType = new TypeToken<ArrayList<Item>>(){}.getType();
ArrayList<Item> items = gson.fromJson(your_json_string, itemsType);
for (Item item : items) {
    System.out.println(item);
}

这样你应该能够正确地创建一个Java对象,包含了从JSON对象中提取的值。

英文:

I have json like this:

&quot;items&quot;: [
{
&quot;value&quot;: 111,
&quot;from&quot;: 1,
&quot;to&quot;: 2
},
{
&quot;value&quot;: 222,
&quot;from&quot;: 3,
&quot;to&quot;: 4
},
{
&quot;value&quot;: 333,
&quot;from&quot;: 5,
&quot;to&quot;: 6
}]

Java class like this:

public class Item{
String from1To2;
String from3To4;
String from5To6;
}

I would like to create one Java object from 3 json objects.

I did something like this:
Deserialize json:

@Override
public Item deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
if (jsonObject.get(&quot;from&quot;).getAsString().equals(&quot;1&quot;)) {
from1 = Double.parseDouble(jsonObject.get(&quot;value&quot;).getAsString());
}
else if (jsonObject.get(&quot;from&quot;).getAsString().equals(&quot;3&quot;)) {
from3 = Double.parseDouble(jsonObject.get(&quot;value&quot;).getAsString());
}
else if (jsonObject.get(&quot;from&quot;).getAsString().equals(&quot;5&quot;)) {
from5 = Double.parseDouble(jsonObject.get(&quot;value&quot;).getAsString());
}
return new Item(from1, from3, from5);
}

if I deserialize, I will get a few Java objects because I have a json array of objects.

run code:

Gson gson = new GsonBuilder()
.registerTypeAdapter(Item.class, new ItemDesarializer())
.create();
Type itemsType = new TypeToken&lt;ArrayList&lt;Item&gt;&gt;(){}.getType();
ArrayList&lt;Item&gt; items = gson.fromJson(some_string, itemsType);
for(Item it : items) {
System.out.println(it);
}

CONSOLE LOGS:

from 1 to 2: 111.0
from 3 to 4: 0.0
from 5 to 5: 0.0
from 1 to 2: 111.0
from 3 to 4: 222.0
from 5 to 6: 0.0
from 1 to 2: 111.0
from 3 to 4: 222.0
from 5 to 6: 333.0

So I have 3 objects

答案1

得分: 2

您需要创建自己的JsonDeserializer。

JsonDeserializer<Item> deserializer = new JsonDeserializer<Item>() {
    @Override
    public Item deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();

        int from = jsonObject.get("from").getAsInt();
        // 您的逻辑
        return new Item();
    }
};

然后,您需要将自定义的反序列化器添加到Gson中。

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Item.class, deserializer);
Gson customGson = gsonBuilder.create();
Item item = customGson.fromJson(json, Item.class);

编辑:

我没有考虑到可能会有进一步的问题,但如果有的话,我附上了完整的解决方案。

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Item.class, new JsonDeserializer<Item>() {
    @Override
    public Item deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();

        JsonArray arr = jsonObject.get("items").getAsJsonArray();
        Item item = new Item();
        arr.forEach(element -> {
            JsonObject obj = element.getAsJsonObject();
            switch (obj.get("from").getAsInt()) {
                case 1:
                    item.setFrom1To2(obj.get("value").getAsString());
                    break;
                case 3:
                    item.setFrom3To4(obj.get("value").getAsString());
                    break;
                case 5:
                    item.setFrom5To6(obj.get("value").getAsString());
                    break;
            }
        });
        return item;
    }
});
Gson customGson = gsonBuilder.create();
Item item = customGson.fromJson(json, Item.class);

System.out.println(item);

输出:

Item{from1To2='111', from3To4='222', from5To6='333'}
英文:

You need to create your JsonDeserializer.

JsonDeserializer&lt;Item&gt; deserializer = new JsonDeserializer&lt;Item&gt;() {  
@Override
public Item deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
int from = jsonObject.get(&quot;from&quot;).getAsInt();
// Your logic
return Item()
}
};

Then you will need to add your custom deserializer to gson

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Item.class, deserializer);
Gson customGson = gsonBuilder.create();  
Item item = customGson.fromJson(json, Item.class); 

EDIT:

I didn't think there might be any further problems, but if so, I am attaching the complete solution.

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Item.class, new JsonDeserializer&lt;Item&gt;() {
@Override
public Item deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonArray arr = jsonObject.get(&quot;items&quot;).getAsJsonArray();
Item item = new Item();
arr.forEach(element -&gt; {
JsonObject obj = element.getAsJsonObject();
switch (obj.get(&quot;from&quot;).getAsInt()){
case 1 : item.setFrom1To2(obj.get(&quot;value&quot;).getAsString()); break;
case 3 : item.setFrom3To4(obj.get(&quot;value&quot;).getAsString()); break;
case 5 : item.setFrom5To6(obj.get(&quot;value&quot;).getAsString()); break;
}
});
return item;
}
});
Gson customGson = gsonBuilder.create();
Item item = customGson.fromJson(json, Item.class);
System.out.println(item);

Output:

Item{from1To2=&#39;111&#39;, from3To4=&#39;222&#39;, from5To6=&#39;333&#39;}

答案2

得分: -1

你可以使用Jackson API来处理JSON,它具有许多用于简化的功能。

英文:

You can use jackson API for handling json which is having lots of function for simplification.

huangapple
  • 本文由 发表于 2020年8月5日 21:42:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63266513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定