将JSON字符串中的值转换为对象。

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

Convert values from json string to object

问题

I have a JSON payload of the format, with each value a list with a single map element:

{
  "redundant_str_1": [
    {
      "attr_1": "val1",
      "attr_2": "val2"
    }
  ],
  "rendundant_str_2": [
    {
      "attr_1": "val4",
      "attr_2": "val3"
    }
  ]
}

Model is:

public class MyObj {
     private String attr_1;
     private String attr_2;
}

How can I map the above response to List<MyObj> by neglecting the keys and taking only elements from lists?

英文:

I have a JSON payload of the format, with each value a list with single map element:

{
  &quot;redundant_str_1&quot;: [
    {
      &quot;attr_1&quot;: &quot;val1&quot;,
      &quot;attr_2&quot;: &quot;val2&quot;
    }
  ],
  &quot;rendundant_str_2&quot;: [
    {
      &quot;attr_1&quot;: &quot;val4&quot;,
      &quot;attr_2&quot;: &quot;val3&quot;
    }
  ]
}

Model is:

public class MyObj {

     private String attr_1;
     private String attr_2;
}

How can I map above response to List&lt;MyObj&gt; by neglecting the keys and taking only element from lists?

答案1

得分: 1

以下是代码的翻译部分:

String json = "{\"redundant_str_1\": [{\"attr_1\": \"val1\", \"attr_2\": \"val2\"}], \"rendundant_str_2\": [{\"attr_1\": \"val4\", \"attr_2\": \"val3\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
List<MyObj> myObjList = new ArrayList<>();

ObjectNode objectNode = (ObjectNode) objectMapper.readTree(json);
for (Iterator<JsonNode> it = objectNode.elements(); it.hasNext(); ) {
    ArrayNode arrayNode = (ArrayNode) it.next();
    MyObj myObj = objectMapper.treeToValue(arrayNode.get(0), MyObj.class);
    myObjList.add(myObj);
}
System.out.println("List : " + myObjList);

输出:

List : [MyObj{attr_1='val1', attr_2='val2'}, MyObj{attr_1='val4', attr_2='val3'}]

希望这有助于您的需要!

英文:
String json = &quot;{\&quot;redundant_str_1\&quot;: [{\&quot;attr_1\&quot;: \&quot;val1\&quot;, \&quot;attr_2\&quot;: \&quot;val2\&quot;}], \&quot;rendundant_str_2\&quot;: [{\&quot;attr_1\&quot;: \&quot;val4\&quot;, \&quot;attr_2\&quot;: \&quot;val3\&quot;}]}&quot;;
ObjectMapper objectMapper = new ObjectMapper();
List&lt;MyObj&gt; myObjList = new ArrayList&lt;&gt;();

ObjectNode objectNode = (ObjectNode) objectMapper.readTree(json);
    for (Iterator&lt;JsonNode&gt; it = objectNode.elements(); it.hasNext(); ) {
        ArrayNode arrayNode = (ArrayNode) it.next();
        MyObj myObj = objectMapper.treeToValue(arrayNode.get(0),MyObj.class);
        myObjList.add(myObj);
    }
System.out.println(&quot;List : &quot; + myObjList);

Output :

   List : [MyObj{attr_1=&#39;val1&#39;, attr_2=&#39;val2&#39;}, MyObj{attr_1=&#39;val4&#39;,attr_2=&#39;val3&#39;}]

答案2

得分: 0

你可以使用Jackson(添加jackson-corejackson-databind的依赖项):

String json = "["
                + "{\"attr_1\": \"val1\", \"attr_2\": \"val2\"}, "
                + "{\"attr_1\": \"val4\", \"attr_2\": \"val3\"}"
                + "]";
    
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
List<MyObj> list = Arrays.asList(mapper.readValue(json, MyObj[].class));

或者,如果在MyObj上添加字段的setter方法或使它们成为public,那么不需要以下行:

mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
英文:

You can use Jackson (add dependencies to jackson-core and jackson-databind):

  String json = &quot;[&quot; +
                &quot;{\&quot;attr_1\&quot;: \&quot;val1\&quot;, \&quot;attr_2\&quot;: \&quot;val2\&quot;}, &quot; +
                &quot;{\&quot;attr_1\&quot;: \&quot;val4\&quot;, \&quot;attr_2\&quot;: \&quot;val3\&quot;}&quot;
                + &quot;]&quot;;

  ObjectMapper mapper = new ObjectMapper();
  mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
  List&lt;MyObj&gt; list = Arrays.asList(mapper.readValue(json, MyObj[].class));

Or, if you add to MyObj setters on fields or make them public there will be no needed the row:

mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

答案3

得分: 0

你的回应是 Map<String, List<MyObj>> 的格式。你可以将其反序列化为给定类型,然后将其转换为 List<MyObj>

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.Data;
import lombok.ToString;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MyObjApp {
    public static void main(String[] args) throws IOException {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = JsonMapper.builder().build();
        TypeReference<Map<String, List<MyObj>>> respType = new TypeReference<Map<String, List<MyObj>>>() {};
        Map<String, List<MyObj>> response = mapper.readValue(jsonFile, respType);

        List<MyObj> myObjs = response.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
        System.out.println(myObjs);
    }
}

@Data
@ToString
class MyObj {

    private String attr_1;
    private String attr_2;
}

以上代码会打印出:

[MyObj(attr_1=val1, attr_2=val2), MyObj(attr_1=val4, attr_2=val3)]
英文:

Your response is of form Map&lt;String, List&lt;MyObj&gt;&gt;. You can deserialise it to given type and after this convert to a List&lt;MyObj&gt;.

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.Data;
import lombok.ToString;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MyObjApp {
	public static void main(String[] args) throws IOException {
		File jsonFile = new File(&quot;./resource/test.json&quot;).getAbsoluteFile();

		ObjectMapper mapper = JsonMapper.builder().build();
		TypeReference&lt;Map&lt;String, List&lt;MyObj&gt;&gt;&gt; respType = new TypeReference&lt;Map&lt;String, List&lt;MyObj&gt;&gt;&gt;() {};
		Map&lt;String, List&lt;MyObj&gt;&gt; response = mapper.readValue(jsonFile, respType);

		List&lt;MyObj&gt; myObjs = response.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
		System.out.println(myObjs);
	}
}

@Data
@ToString
class MyObj {

	private String attr_1;
	private String attr_2;
}

Above code prints:

[MyObj(attr_1=val1, attr_2=val2), MyObj(attr_1=val4, attr_2=val3)]

huangapple
  • 本文由 发表于 2020年7月28日 19:42:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63133322.html
匿名

发表评论

匿名网友

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

确定